Webservice expecting JSON, sending multipart-form data - c#

I am trying to make the upload of files in a asyncronous way. I am currently using jquery.form plugin and using the ajaxSubmit method. Backend consists of getting this uploaded document and insert it into a document library. No problems in that part. Now when I try to do an upload, I get a 404 bad request error. The webservice expects JSON from a request. I noticed that this isn't the case, as in the request payload I get something like the following.
Content-Disposition: form-data; name="file"; filename="Json45r11 (1).zip"
Whic isn't a JSON, so I think this is why I get a bad request.
Webservice definition of backend method is like this:
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.WrappedRequest , ResponseFormat = WebMessageFormat.Json)]
SuccessUpload uploadDoc(string id);
Front end submit looks like this:
$('#form').ajaxSubmit({url: 'backend Method', type: 'post',data: JSON.stringify({id:1})});
Is there a workaround all this? Any help is appreciated, sorry if bad english not native language.

The jQuery.form plugin uses multipart/form-data encoded request when uploading a file which a classic ASMX web service cannot understand. You could replace your web service with a generic ASHX handler (IHttpHandler) which would allow you to handle any request format. Or even better if you don't want to get as low-level as handlers you could use some of the new frameworks such as ASP.NET MVC, ASP.NET WEB API, WCF, ServiceStack, ... which all will happily handle multipart/form-data encoded requests.

Since the webservice expects a JSON, in the declaration of your method just put that it receives an object of type STREAM.
this should work:
[OperationContract]
SuccessUpload uploadDoc2(Stream data);

Related

Consume simple WCF service in a client request

I'm trying consume my wcf application with Postman (or simple ajax request), but for some reason, the request always return me:
STATUS 400 Bad Request
But, from the VS test client, my service works.
Interface
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "general/")]
MyModel getCourse(int idCourse);
My Class
public MyModel getCourse(int idCourse)
{
return null;
}
Some one has an idea? Thanks.
I was having a similar issue trying to test my WCF service in Postman and I used Chrome's developer tools to figure out the right parameters to pass into the Postman request.
Right-click your page in Chrome and select "Inspect Element"
Select the "Network" tab and reload a page that executes your WCF request
Select the request from the left margin of the "Network" tab, and view the "Request Headers" associated with that request
In Postman, add headers that match those that are shown on the "Request Headers" and make sure that the data you pass into the call on Postman matches that of the "Request Payload" listed in Chrome.
Your VS test client may has an app.config with settings used by runtime to inject into the CLR proxy classes in order to generate a proper SOAP request or Web API request. You may use some Web traffic diagnostic tool like Fiddler to inspect the content of a valid request from your VS client and the bad request from Postman, and compare the difference, and consult what available in VsClient.exe.config, and make appropriate change in Postman.

How to POST JSON HTTP Request to RESTful API made by WCF

I am trying to make Android consume a simple WCF webservice made by my self. Here is my WCF Service definition:
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/UploadCallLog2")]
[OperationContract]
String UploadCallLog2(String number, String cached_name, String duration, String date, String line_number);
I have two questions:
1. And what should my HTTP Request Look Like? What kind of Content type should I choose when add the request header?
2. Is there the correct way to put input param in body as JSON and the webservice can auto detect the value of input parameters?
Fred
I would suggest using an MVC project for this over a WCF service.
The controller can return a JsonResult, the MVC library contains Json helper methods to serialize and deserialize the json objects into c# objects if the properties match.
Also this then allows the MVC based service to be called from any client that has support for XmlHttpRequest using ContentType as "application/json". You can use either HttpGet or HttpPost depending on your request type and security of data under SSL as well. You can also take advantage of the authentication model to secure your methods.
This just makes for a really clean implementation that doesn't have any complex server and client configurations. More information regarding similar approaches is the new Web API in MVC 4.

WCF 4.0 - Get Parameter from URL or POST Body

I have a WCF endpoint and I have setup my URI Template as such:
UriTemplate = "?token={token}"
If the token parameter is not in the URL, I want it to attempt to pull it from the POST body.
I am testing my POST calls and putting the token in the URL works great, but fails if I put it in the POST body instead.
Is there any way to handle this? I was doing it before using a ServiceAuthorizationManager, however, there wasn't a great way to send back friendly error messages.
You can get access to the RequestBody as shown below:
OperationContext.Current.RequestContext.RequestMessage.GetBody<string>();
Hope that helps you :)

c# app: Is it possible to implement a JSON interface?

I've built a simple C# app (.Net 4.0 + WPF) which can send and receive JSON messages via TCP sockets.
As a next step, it should be possible that JavaScript apps on websites and PHP scripts can send and receive JSON messages to/from my app. Is that possible?
Since JS/PHP will use stateless HTTP connections, how should a request to my app work, for example, should the JS/PHP apps send a JSON message to my app and my app response (HTTP response) with a JSON message? Is that even possible? And should I use GET or POST method to send the JSON messages to/from my app?
Hope my questions do not cause too much confusion ;-) I but I appreciate every tip, clarification or feedback you can give me.
Mike
You can accomplish this via a .NET web service using special JSON directives on the web method, e.g.
[ScriptMethod(UseHttpGet = true, ResponseFormat=ResponseFormat.Json)]
public string DoSomething(string param1, int param2)
{
// Do Something
}
When the ResponseFormat.Json property is specified, the data returned will be serialized into the appropriate JSON format. Also note, in order to recieve a true JSON response, you'll need to set your content-type to "application/json" from the requesting application. Otherwise, the method will attempt to wrap the response in XML.
Also, I am enabling a HttpGet on this method so that you can post via a query string to the method, e.g.
http://www.example.com/service.asmx?param1='Hello'&param2=1;

WCF XmlSerialization Attribute(POST)

I currently have a WCF service to consume a remote REST service with the following:
[ServiceContract]
[XmlSerializerFormat]
public interface IMyApi
{
[OperationContract]
[WebGet(
ResponseFormat = WebMessage.Xml,
UriTemplate = "RemoteServicePage.jsp")]
MyNewClass Send();
}
The nice part about this is the XmlSerializerFormat attribute. Automatically deserializes a response into the return type of the method(ie, POX response => MyNewClass).
I've been unsuccessful, however, in finding any samples of the reverse. I'd like to post a POX request to a given service. I'm curious if there's a similar way to pass an object to a WCF service which in turn makes the post request to the target.
Any thoughts are greatly appreciated.
UPDATE
Just a clarification of the question:
Is it possible to post an object to a web service via WCF(which handles the serialization)?
UPDATE
I believe Steve touched on what I believe is the right direction below with using the WebInvoke method and attribute RequestFormat to achieve what I'm looking for. I guess I want to point out I'm not hosting a web service that allows for posting, but rather trying to post to an external web service(ie, a remote *.jsp) using WCF.
WCF allows for easy consumption and access of external web services and this is something I'm familiar with. I've never attempted to post a stream or object to an external source however(posting via UriTemplate is straightforward).
I don't understand. Why not just use HttpWebRequest? One of the benefits of doing REST over HTTP is that you get to use standard HTTP libraries. Doing a POST with HttpWebRequest is relatively trivial. Why do you need WCF? If you want to serialize an object into your POST body, then you can do that with either the DataContractSerializer or with the XmlSerializer.
If you really don't like that option, then look at the new Microsoft.Http.HttpClient class that is in the WCF Rest Starter Kit Preview 2. It is a very nice client library and despite its name and packaging, it does not even have a dependency on WCF!
This answer is based on your second update. I only say this because your initial statement of "I currently have a WCF service to consume a remote REST service" makes no sense. You cannot declaratively define a remote interface that you want to consume. The term WebInvoke is not what you are thinking, it is simply a catch all attribute for handing non GET requests. WebGet and WebInvoke both handing incoming requests.
If you want to consume a remote "REST" interface then you need to use HttpWebRequest or the new HttpClient class.
I don't think you understand the meaning of XmlSerializerFormat. It means that the XML Serializer should be used instead of the Data Contract Serializer. Both will serialize to XML.
Use the RequestFormat attribute. For JSON, this would be
[WebInvoke(Method = "POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
ResponseFormat = WebMessageFormat.Json,
RequestFormat = WebMessageFormat.Json)]
Good luck

Categories