POST method, error 400l bad request. asp.net - c#

I'm trying to send data from my iPhone to a windows server 2008.
I found a tutorial, but I'm unfamiliar with asp.net.
So this is my code (in asp.net)
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "InsertEmployee?names={name}&lastnames={lastname}",
BodyStyle = WebMessageBodyStyle.Wrapped,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json)]
//ResponseFormat = WebMessageFormat.Xml)]
//method
bool InsertEmployeeMethod(string name, string lastname);
//
and, I tried testing the installation with "postman", software that let me see the errors and checks in the Method. I sent a test of the code via postman.
And in Google, like this:
http://192.168.1.209/JsonWcfService/GetEmployees.svc/InsertEmployee?name=ildaguin&lastname=pregunton
That returns an Error 400 (Bad request).
How do I resolve this?

One way 400 Bad Request occurs is a syntax error. More details would be helpful including the message you are sending with Postman and the error returned if an error is returned.
If an error is not returned in Postman, then I would compare that to the message right before it is being sent in debug from your code. I can help you out with both if you can post additional details / code.
It is likely that you are missing some information or there is some spelling issue in the request, is a header variable required perhaps ( maybe Bearer token ). Are some words not case correct?
Good Luck

Related

Error Deserializing WCF POST Request With Multiple Parameters

i did search before posting this question and none of the answers helped me
i am hosting a WCF web service on IIS and using GET and POST in it successfully. the error is only showing when calling a POST web method with multiple param
Example:
**//this fails**
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, UriTemplate = "test", BodyStyle = WebMessageBodyStyle.WrappedRequest)]
String test(String p, String credential);
**//this works**
[OperationContract]
[WebInvoke(Method = "POST",UriTemplate = "test")]
String test(String p);
the code behind simply returns a string for testing
I am receiving the following error:
The server encountered an error processing the request. The exception
message is 'Error in deserializing body of request message for
operation 'test'. The OperationFormatter could not deserialize any
information from the Message because the Message is empty (IsEmpty =
true)
i am testing the following web methods on POSTMAN
Parameters passed are random string:
p: tt
credetial: ghdhdj
WCF doesn’t support form-data by default, we merely pass the parameter by using the Wrapper element when we use Http_Post request.
As you mentioned, we should use the below code to wrap the multiple parameters.
[OperationContract]
[WebInvoke(BodyStyle =WebMessageBodyStyle.Wrapped)]
string GetData(string value,string value2);
And then we can pass the parameters with JSON format.
{"value":"ab","value2":"cd"}
Screenshot.
Feel free to let me know if the problem still exists.

Is it possible to use both GET and POST in a same method?

I would like to know, in a wcf rest service is it possible to use both HTTP POST and HTTP Get in same method? I mean to say that a client page can either use post or get to invoke my method.
My client wants me to implement a method in this way.
As our API is a "RESTful" service we should be able to use both GET
and POST with this method. The parameter can be placed in the URL
of a GET request and also in the Header section of the GET request. When
using a HTTP POST with this method the parameter can be
stored in the header section or the body.
Is it possible?
Lets do it by writing code! Suppose you have a method!
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "Leads",
ResponseFormat = WebMessageFormat.Xml,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
[WebGet(UriTemplate="/Leads")]
Result AddLeads(ReqLead[] rl); // This is our method.
When you will run your service, it will compiled and run successfully and browser will display you a page.
Now green arrow pointing is my Service name. By cliking on it will redirect you an error page and it will make an idea clear to you! See the image below.
I hope it will give you an idea. Moreover! In you [OperationContract] you will define only one method type, whether GET or POST. You can't have both.
Thanks

WCF HTTP GET parameter causes bad request

I have a WCF service with the following operation contract:
[OperationContract]
[WebGet(BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "/VerifyKeys.json/{customerKey}/{userKey}")]
[return: MessageParameter(Name = "MyDetail")]
MyDetail VerifyKeys(string customerKey, string userKey);
My method is like this:
public MyDetail VerifyKeys(string customerKey, string userKey)
{
...
return _myDetail;
}
My request is like this:
http://mydomain.com/MyService.svc/web/VerifyKeys.json/FE3D0F1D-5B8B-4677-B332-70B7ABA80A97/08F4349A-30E5-457D-F2BD-70A23CE17F41?deviceId=66345ec6-a5fe-4b5f-8cf2-1b0d8c344dc2&deviceToken=AgTGERCBaS3d8n2QWxF9EtwcLktIoygoXpc8Y42ObZWja3RSjN%2bFBeshaY4ASainj3MusBbVopXbUFQrrgXUOSkAbOA7tChNKOFNKQ2gB8sEfCe5Du9BZufW4bAP5312MKRqV8g%3d&deviceType=Pink24
I have different versions of my application calling this method. Rather than create a new method, I have used a query string at the end. By parsing the url, I can get the additional parameters I need. ie. deviceToken, deviceId, & deviceType
My request worked fine while the deviceToken parameter was smaller. Now the company providing me with my device token has made an excessively huge one. And now my request returns Bad Request 400.
AgTGERCBaS3d8n2QWxF9EtwcLktIoygoXpc8Y42ObZWja3RSjN%2bFBeshaY4ASainj3MusBbVopXbUFQrrgXUOSkAbOA7tChNKOFNKQ2gB8sEfCe5Du9BZufW4bAP5312MKRqV8g%3d
If I remove these characters from the end of my query string, the request goes through successfully. "Q2gB8sEfCe5Du9BZufW4bAP5312MKRqV8g%3d"
I have done some research and discovered that the max for a parameter is 255 characters. My device token is only 140.
To add to my confusion, if I change the order of the deviceId and deviceToken parameters, then I must shorten the deviceId parameter to send successfully. Another point of interest is that if I try to shorten any of the other parameters, then my request still fails. I must always shorten the second parameter.
Has any one else had similar problems and found a solution?
How can I send my looong device token via a query string at the end of a path?
It's possible it's the length of your query string itself, not the parameter.
Try adding
<httpRuntime maxQueryStringLength="2500"
maxUrlLength="2500" maxRequestLength="2500" />
to your config and see if the error persists
I found the solution after posting this question. Such is often the way.
The device token was getting saved to a field that was NVARCHAR(100). Previously this was enough. The device token can now be at least 140 characters. I changed the field to NVARCHAR(255). The problem is fixed. No more Bad Request 400.

Why does this simple RESTful WCF Service fail with a 404 error?

Using this tutorial:
http://www.codeproject.com/Articles/105273/Create-RESTful-WCF-Service-API-Step-By-Step-Guide
I can get a Directory Listing to display when I run the app from VS 2010.
I can paste the URL that is displayed in the IE Browser that VS invokes (http://localhost:4841/) into an outside-of-VS instance of IE and see the same thing. However, if I append "/xml/123" or "/json/123" as shown in the tutorial, so that the URI is "http://localhost:4841/xml/123" or "http://localhost:4841/json/123", I get:
*Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /json/123/
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272*
If I append "RestServiceImpl.svc" to the URI, so that it is "http://localhost:4841/RestServiceImpl.svc" I get the "Service" page ("This is a Windows© Communication Foundation service. Metadata publishing for this service is currently disabled."); but appending "/xml/123" or "/json/123" leads to the same 404.
The most pertinent code (taken straight from the 5-star tutorial) is:
[ServiceContract]
public interface IRestServiceImpl
{
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "xml/{id}")]
string XMLData(string id);
[OperationContract]
[WebInvoke(Method = "GET",
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Wrapped,
UriTemplate = "json/{id}")]
string JSONData(string id);
}
I think you're missing the actual service, eg. RestServiceImpl.svc
So it would be something like:
http://localhost:35798/RestServiceImpl.svc/xml/123
Okay, I solved the dilemma by replacing, in Web.config, this:
<service name="RestService.RestServiceImpl"
...with this:
<service name="REST_JSON_POC.RestServiceImpl"
(and the other place where "RestService" appears with "REST_JSON_POC")
("RestService" is what the tutorial had, but REST_JSON_POC is the name of my project)
But now I have another problem, for which I will create a new question (the "xml/123" now works fine, but "json/123" prompts to download a file, named "123" which has the expected string in it).

Multiple parameters passed in WCF client don't work (even when WebMessageBodyStyle is Wrapped)

Hi fellow StackOverflowers,
I've got a WCF service wrtten C# that i can succesfully consume from things like jquery.
I want to be able to consume it by adding a web service reference in C# and making calls in the code. Everything was rosy, until I added multiple parameters. When I try to call any Service method, I get this error:
Operation 'GetStopNames' of contract 'IPublic' specifies multiple
request body parameters to be serialized without any wrapper elements.
At most one body parameter can be serialized without wrapper elements.
Either remove the extra body parameters or set the BodyStyle property
on the WebGetAttribute/WebInvokeAttribute to Wrapped.
I googled and searched StackOverflow for ages, but everybody seemed to have their problem fixed by setting
BodyStyle=WebMessageBodyStyle.Wrapped
in the WebGet / WebInvoke attributes.
An example of one of my service methods in the interface:
[OperationContract]
[WebGet( BodyStyle=WebMessageBodyStyle.WrappedRequest
, UriTemplate = "GetOperators?appKey={apk}"
, RequestFormat = WebMessageFormat.Json
, ResponseFormat = WebMessageFormat.Json)]
ResultList GetOperators(string apk);
Is there something wrong with this?
I'm simply calling
ServiceReference1.PublicClient c = new ServiceReference1.PublicClient();
c.GetOperators("XXX");
inside the client, and it's breaking on the second line.
Any ideas? If there is any more data you need to help answer me, just add a comment :)
EDIT:
here are the excerpts of relevant bits from my Web.config files
http://pastebin.com/CyQNG6wk
EDIT:
shortcut to serviceContract that I linked in comments
http://pastebin.com/bvGmGtfd
I ended up switching to using WebApi but I'm keeping this question open since I'm still not sure why it was failing.
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "GetOperators?appKey={apk}",
BodyStyle = WebMessageBodyStyle.Wrapped,
ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json)]
ResultList GetOperators(string apk);
In the .svc file make sure Service="Developer_Portal.Public"
Its the problem in GetStopNames. I assume it is Http Get (WebGet). Make sure all the parameters it accepts are defined in uri template
GetStopNames(string p1, string p2, string p3)
uri = "GetStopNames/{p1}/{p2}?param1={p3}" or GetStopNames?param1={p1}&param2={p2}&param1={p3} or whatever combination
You cannot generate proxy for rest by adding service reference. Do you have soap based service with same interface also?

Categories