POST JSON to webservice using WebClient C# - c#

I am working on a desktop application which calls some web services via WebClient POST requests. These same web services are used in web application also.
I am facing a strange problem where in my desktop application request was successful and I got response but some of my requests parameters were not saved. But same request is updateing all the parameters we I call them from web application using jquery.
In web application I am calling web service like this
$.post("/MyService/Account/Register",accountModel, function (data) {
});
and I stingify my json object that is accountModel, my request looks like this when console.log
{"Name":"Lorem","Email":"abc#abc.com","interest":"[\"1\"]","sectors":"[\"1\",\"2\"]","subscribe":false}
Now when I used same request string to post data from my desktop application all the properties like name, email and subscribe were saved but interest and sectors were not saved.
I want to figure it out that why same request object is working via jquery and not in C# webclient.
Here is my code that I used to post data using WebClient
WebClient client = new WebClient();
string json = string.Format("{{\"Name\":\"{0}\",\"Email\":\"{1}\",\"interest\":\"[\"{2}\"]","sectors":"[\"{3}\",\"{4}\"]","subscribe":{5} }}","Lorem","abc#abc.com","1","1","2","false");
client.Headers[HttpRequestHeader.ContentType] = "application/json";
string result = client.UploadString("http://Server.com/MyService/Account/Register", json);
Please someone help me to resolve this issue that I am not getting any error but some of my parameters were not updates.
I want to clear that I do not have any code or documentation access to web service.
UPDATE
As per Jasen's comment here are requests captured with fiddler
JQuery request
POST http://Server.com/MyService/Account/Register HTTP/1.1
Host: server.com
Connection: keep-alive
Content-Length: 463
Accept: */*
Origin: http://server.com
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://server.com/MyService/Account/Register/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
Cookie: .ASPXAUTH=7A14FC68B72078BAE43A623B94A901180C72093CCE222BBD98EE2AE7E2612078D1E3B7D8860905A4F7B2D75FD67E9274A0A5C40760A5AF703F970504380EBAF8B3D09A15F0B70090ACF4882DC58885F7CF12473BF55647840F3080ADD2C19249
Name=Lorem&Email=abc#abc.com&interest=%5B%221%22%5D&sectors=%5B%221%22%2C%222%22%5D&subscribe=false
WebClient Request
POST http://server.com/MyService/Account/Register HTTP/1.1
Content-Type: application/json
Host:server.com
Cookie: .ASPXAUTH=F586C63F64186E13EB6EC19AAB25A531A0EDA5B7B601013550ADD629C1481EC3F080DDB5F06D691CB8F81EE8631EF8859F82CF7DD3F2ED2A597AA971A53E80141EDD6EA549784AD7EAE8E144F0CD3196A44316F29C08E0C5383A7231A1B6C5EF
Content-Length: 536
Expect: 100-continue
{"Name":"Lorem","Email":"abc#abc.com","sectors":["1","2"],"interest":["1"],"subscribe":false}
Shall I send my webclient request as URL encoded string like we can see in jquery request?

Finally I got the solution with help of fiddler. Thanks to Jasen for suggesting fiddler to see requests
Here is my working code
WebClient client = new WebClient();
string result = client.UploadValues("http://Server.com/MyService/Account/Register", new NameValueCollection()
{
{"Name","Lorem"},
{"Email","abc#abc.com"},
{"interest","[\"1\"]"},
{"sectors","[\"1\",\"2\"]"},
{"interest","false"}
});
Yes I used UploadValues method instead of UploadData or UploadString. Also note that I have removed the content type json declaration from my code.

Related

.NET Core 1.1 MVC Controller method not getting called

I have a .NET Core 1.1 MVC controller that somehow isn't getting called correctly when a request comes in.
The controller method looks like this:
Although I don't know if that really matters, because I have debugging lines in the controller's constructor (and have run in debug with breakpoints in the constructor, as well), and it looks like even the constructor is never getting called.
The application output contains a line like this, when the call comes into the server:
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action Namespace.NameController.GetData (AssemblyName) in 0.9161ms
Something that is suspicious there is that most of the lines I see logged like this for other controllers being called contain the argument information, as well, and this one doesn't.
I'm not getting an error from the client side, instead I'm getting a success response with an empty body. It's almost like an empty response is getting returned before any of my controller's code actually runs.
Here are the details of the request/response (the response body is empty):
Request URL: http://localhost:61410/path-to-controller/GetData?xtype=xtypeargument
Request Method: POST
Status Code: 200
Query Url
xtype: xtypeargument
Request Headers
accept: */*
Origin: http://localhost:61410
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Authorization: bearer <bearer-token>
Referer: http://localhost:61410/path-to/index.html
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8
Response Headers
Server: Kestrel
Access-Control-Allow-Origin: *
X-SourceFiles: =?UTF-8?B?...?=
X-Powered-By: ASP.NET
Date: Wed, 06 Sep 2017 14:08:10 GMT
Content-Length: 0
Any ideas of what might be going on here?
It turns out that the controller's constructor had arguments that were expected to be provided by Dependency Injection, but that weren't. Somehow this caused the behavior I was seeing, although I still don't really understand why I wasn't getting exceptions instead of these empty responses. Anyway, I fixed the code and it's working now.

Request format is unrecognized when invoking web method remotely from JavaScript file

I have a problem with invoking an ASMX web method on a remote server through AJAX in a stand-alone JavaScript file.
I use AJAX to call web methods in two places; in .aspx pages (JavaScript embedded into the page) and in a stand-alone JavaScript file.
The website and web service is hosted on a remote server. The problem is that when the web methods are invoked through the stand-alone JavaScript file, I receive a 500 internal server error with the following error message:
Request format is unrecognized for URL unexpectedly ending in /MyWebMethod
I have found out the following about the problem:
The error occurs only from the stand-alone JavaScript file. If I run the script embedded in an .aspx page it works fine.
The error occurs only when invoked remotely. If I run the script from a browser on the server it works fine.
Adding protocols as suggested in this answer solves the problem, but this is not a feasible solution as I have no control over the Web.config where the solution is deployed.
I added logging in the web method to see if it was entered when the error occurs. It did not enter the method body.
The AJAX and web methods in question follow this pattern:
function getAjaxResponse() {
$j.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
cache: false,
async: true,
url: "Path/To/Webservice.asmx/MyWebMethod",
dataType: "json",
success: function (data) {
// do stuff
},
error: function () {
// do stuff
}
});
}
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public string MyWebMethod()
{
var obj = SomeMethod();
return obj.JsonSerialize();
}
So to sum up: I have identical code in .js and .aspx files. When visiting the pages remotely, only AJAX invoked from .aspx files works. When run locally, both .js and .aspx works.
Does anyone have any idea what might cause this and how it can be solved? I am perplexed that it works locally or when called through .aspx, but not remotely when called through .js.
EDIT: Here are two HTTP requests:
Locally using Firefox (working)
Host: lwepitest75
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0
Accept: application/json, text/javascript, */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
Referer: http://lwepitest75/episerver/Cms/
Cookie: ASP.NET_SessionId=kljsmiofrw21agtcns2fojgn; .EPiServerLogin=13A4F4219A61436A4D33BF118EE4523DE1816A927A39968EDE7EBE1D3DEA8949E39BC7FB047ADE9CE1446FD8134E60CF5A27E0D6BB0098C4FF6D81BF91B134285F0AFAE9C7955C1565EA8C4A2CBE266F722A7950D7E1FB169156DC6D2CD0BF1FEB290AD26F6C935CDD1FE06C9260C5E8A62E5A1897C0C7AD55F1346603C3B5C2; .ASPXROLES=wiPu0FPvbdZVl2g_LZzYK70vb-cg1jl3I6QwspX9dplAfk6Gkp81sqcZ1qrJkGPtfYU-4IYvP5FFLjV8teEiExtRH8jpQryhLCoqAkA6HaezZvHFDO63krXiSUTYalnVYElWivP-yVkhqnHJsxhURDNJQeLNs8sCM5LZKNTGzAjPTxeQjwDO41jeG7OHy9KwKs3lYmvrgNu-RnygBYq0zad0x3x9sNY4UWNBV2j2_421IeP77bgtzyTypdCju_gma_hz-a_OUogwlvpqTwTcgZqfD1mi3zHm0DEolIWiJkhU_6XOzvaCcgSvOZtZ69tIPGQ3VKku0jKEYli_bG7uaHqgoCjcEUqvaIa7IbrSMA3SeTn4jzrCf1z94wl2s5aLQ8eAaUoZTx2alwa6YX7D_O43MEA_6_tU-71C0xooJ0eZWFzmUS8Rek4UcA7tdJvJobp9ZCxHuNg6RmxJ8foS4g2LGO82mjK-s5LBcaAOkpm0GqUgeN0hSdq19pPwVDC0lgV2O8eFy8RVVUQ-h339WFKMnbx20aO0Ahjo8QqF1bYEEysZaMT_xWxnpnQCQibuIq6G5J8_7-IqbmK5I-dd0c6wgURLWDsGjbg4wrp534b9elPJGW44lXrjkFVm4ElQzeNJHQ-kxW-M0qIJrFAHtoSybQ7zlx0giuBGJeFwsgXkIbVJSyVjeaQa2Xk_6ttRg16Z884kWkr1_0MV5gkpEJAkNYop-9RC3IdTS0bsIwQTcoSbD9ZmaF5C_7nSVX4GVroXTnnV0OaM41S6W5KX_pQ_BVxKvKk-1FuGnjoc4GZd0Gg9J1mqsKo5Q4nxSbf5bvsFK6x5K1noNUY3kWw4gg2; __epiXSRF=PfB/aDsSD4U/surUSQ5zCVg+xYzK9P4YOdMckQN9aOg=
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Content-Length: 0
Remotely using Chrome (not working)
Host: lwepitest75
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.130 Safari/537.36
Accept: application/json, text/javascript, */*
Accept-Language: da-DK,da;q=0.8,en-US;q=0.6,en;q=0.4
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
Referer: http://lwepitest75/episerver/Cms/
Cookie: ASP.NET_SessionId=o1e5wycnmicp24fmjnyf0pmo; __epiXSRF=IMktMh1Pgy5shyooquYvJwXU5a7SedjZWBgxmNzwiKw=; __RequestVerificationToken=gWQQtm60CSAvZikKqvFn2OZO9abqMfe8mvUIskLH5jj9MDW35_RQCkUAtsVIxX6lsqw7g8oWSR-eTBQg-mrPXVBRJZFU24HFaP9dTIHmFijPmt-bj4JJ9ofH5wwB0-BDrP1xiMdOb_FvvaVH8-iv6w2; .EPiServerLogin=3A1FC04DC74F4864A9D5E13A515771C94775645BD4616C8A305CBF26DD1BC3EF6704FC3012639F9B945816774B4252C32B38D6A19341341F28D1A436B05F0A3DB117FD053CBE8F30A4E97BE0A3EE06F2A698DC2D1F6B556E3974748B3607D3D6E8319594FDA59EE33EA59BB2F566DEF740D20C18147FFB4C0AFABDD0BDDEC85C; .ASPXROLES=bKm0JfD2Y9zzEdavxDERJltj8arOT9Jqv__2B2FNtD6XRhkJqekrHbQTrk6UBd7PhKixI92jbHL6-ufepok4-FlWEyN3RJ8XMIM7Vsbx1EZAboSz0IDKhZXVIPc_arkaW3Q-SZbSmsqRQhRYoVLE7huW3xUVvJhx26jSmSANgszKWAD4v18B3KupP7Uk68RfhSEnC_IGS01U-4wbfkUMzB2ByzyvUqnRykSKzczr7TdF8gItkGWzIxcy8zSVg8MOBrCyBmR_SwIcsy7vIuAOADENnIJXuZNtJ1-yZ08BPgK867Sm1UJ3d2RWD4v7rrDiI0BraY97MqFK6LuZBD9h_V9eBrMgnbDd4dEnDQwm-ryHsmyxVUswM45LMHya-aZy9wbLFrMo4IU9VqS8T92_2XbzFXkw4lBbYRrguipUwuOMmpAHuuuJIWz8akvbJhF9eQeUEDsK-lHRkEI-oPVfvkRKXXOjOm542hxYXE8fb7BmMFcr27ayU2fCy1Tk3IbdLI17yvdIJhu5rdP9hdQ7ZZR06ErMKgmSW_0-k7BtTIPVfWty6TdORretE2PKSfM8Wd9AAXI9wsvcmj9t0Uahlvql5oiRZ0HYulxNKdIYl9IKTu5V8wPedygDAJSBqYEZnzgf6YFpCQBFIivunuHtRbicwBeSTmKtdblF1wU1ZhPc5tPN_Num-jbvpLONLYeR6zHBfgkgbL-NNTIO-D_wTwy-F1yhK5sITbcPptfwvsz6l1dNNFuriMKz1rtD4n8xsBptGXUQflXzWlzBhjddcE6R7BGGGsB-hhsb-4oNRCFjyOMD3HmdLF7lIFM2G6-9C5V2qCrK7Ob9KcPm-X4vSA2
Proxy-Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Content-Length: 0
Origin: http://lwepitest75

Get html result from web page

I am planning create a movil application (for fun) that should use the result from this web page (http://consultawebvehiculos.carabineros.cl/index.php). is there any ways to create a instance of a browser in my Net code and read this result and publish it using a web service..
something like:
var IE= new broswer("http://consultawebvehiculos.carabineros.cl/index.php");
var result=IE.FindElementByID("txtIdentityCar").WriteText(YourIdentityCar);
publicToWebSerivce(result);
Update:
Using Fiddler i can see that http post is somthing like that:
POST http://consultawebvehiculos.carabineros.cl/index.php HTTP/1.1
Host: consultawebvehiculos.carabineros.cl
Connection: keep-alive
Content-Length: 61
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Origin: http://consultawebvehiculos.carabineros.cl
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17
Content-Type: application/x-www-form-urlencoded
Referer: http://consultawebvehiculos.carabineros.cl/index.php
Accept-Encoding: gzip,deflate,sdch
Accept-Language: es-ES,es;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3
accion=buscar&txtLetras=CL&txtNumeros1=sk&txtNumeros2=12&vin=
May be i need some .Net class like webclient in order connect with the php page...no sure.
UPDATE: I finally i found the solution using Fiddler to know the total parameters and I've used the code from http://www.hanselman.com/blog/HTTPPOSTsAndHTTPGETsWithWebClientAndCAndFakingAPostBack.aspx
If your are just interested in scraping the page, I suggest using Html Agility Pack.
If you also want to display the page, then you could use the WebBrowser control.
We've been using http://htmlunit.sourceforge.net/ for similair tasks. It allows you to send requests, receive response/status code/etc.
(it's a Java lib, so you could either google for a .Net port or use a converter to convert Java assembly into .Net assembly - see http://blog.stevensanderson.com/2010/03/30/using-htmlunit-on-net-for-headless-browser-automation/ for guidance. We've used the convertion approach).

Download file by Javascript postback in C#

EDIT:
I´ll be more specific. I want to do a script to download a group of files every day.
To do this programmatically, i need to click in a javascript button.
It´s simple when is just put the URL in WebRequest class, but in javascript button i don´t have the URL. How can i mount this URL?
Request (by Fiddler):
POST /SomeSite?Something.aspx HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Referer: http://www.Site.com/Stackoverflow/SomeSite?Something.aspx
Accept-Language: pt-BR
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)
Content-Type: application/x-www-form-urlencoded
Accept-Encoding: gzip, deflate
Host: www.Site.com
Content-Length: 10616
Connection: Keep-Alive
Pragma: no-cache
Cookie: idioma=pt-br; WT_FPC=id=187.16.81.13-3324702672.30186643:lv=1320587789589:ss=1320587578749
__EVENTTARGET=ctl00%24contentPlaceHolderConteudo%24lnkDownloadArquivo&__EVENTARGUMENT=&__VIEWSTATE=%BlaBlaBla
Here you can see the _EVENTTARGET that is using postback with a link Button which name is "lnkDownloadArquivo". So far I understand you want to simulate same download request without button click. if so then you can check here a solution .
http://ciintelligence.blogspot.com/2011/01/fetching-aspnet-authenticated-page-with.html.
here you can get idea how asp.net button post back request works.
The built-in class you need is the HTTPWebRequest (or WebRequest) class. To create one, call System.Net.WebRequest.Create() and pass your URL, add the appropriate headers using the Headers collection, write to the Stream retrieved from WebRequest.GetRequestStream(), then retrieve the response using WebRequest.GetResponse(). From the retrieved response object, you can get the response Stream using WebResponse.GetResponseStream(). The Stream can then be read from like any other Stream object.

Removing a line feed from the header in of a c# web request

I need to remove the last line feed from a http webrequest in order to communicate with an json-rpc service.
The request which .net generates looks like this.
POST http://localhost.:8332/ HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.1)
Authorization: Basic dGlwa2c6dGlwa2c=
Host: localhost.:8332
Content-Length: 42
Expect: 100-continue
Connection: Keep-Alive
{"id":1,"method":"getinfo","params":[]}
What I would need would be this (notice the missing line feed after last header value and the begin of the json content):
POST http://localhost.:8332/ HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client Protocol 4.0.30319.1)
Authorization: Basic dGlwa2c6dGlwa2c=
Host: localhost.:8332
Content-Length: 42
Expect: 100-continue
Connection: Keep-Alive
{"id":1,"method":"getinfo","params":[]}
I can't find anything where I could manipulate the header which is actually sent to service.
See http://www.bitcoin.org/smf/index.php?topic=2170.0 for more background on the problem...
finally resolved my (core) issue. the problem with my communication with the rpc service, was that I had not set content-type. The service was requiring a content-type of "application/json-rpc" to work properly.

Categories

Resources