开发者

Cannot upload a file to a webservice and get the response in Json format

开发者 https://www.devze.com 2023-01-11 02:47 出处:网络
I have a simple webservice that I would like to upload a file to.The problem is that I need the response in json.

I have a simple webservice that I would like to upload a file to. The problem is that I need the response in json.

Form my experience in order to get a response in Json my request has to have a content-type of 'application/json'. But ofcourse this cannot be the case with a file upload since the content type will have to be 'multipart/form-data'.

In my Json i want to return a value showing whether successful and a filename.

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public TyoeOfSomeObject UploadFile()
{
    // Get the f开发者_如何学Pythonile from the context and do something with it
    HttpPostedFile httpPostedFile = HttpContext.Current.Request.Files[0];

    // Return either a string or an object to serialise with the required values
    return SomeObject;
}


I was having the same issue, and resolved it by setting the response's ContentType and calling the response's Write() function:

C#

String j = jsonParser.AsJson(obj);
Context.Response.ContentType = "application/json; charset=utf-8";
Context.Response.Write(j);

VB

Dim j As String = jsonParser.AsJson(obj)
Context.Response.ContentType = "application/json; charset=utf-8"
Context.Response.Write(j)


You could set the return type of your function to a string and then use some JSON serializer to serialize your object to JSON and return it as a JSON string. For JSON serialization I use Jayrock I believe ASP .NET has its own JSON libraries now as well.


You can declare your web method with byte[] as an output parameter. Then you can set ContentType and return any data you want.

If you use WCF instead of ASMX web service you can return Stream or Message in such cases (see Returning raw json (string) in wcf. You can try also return Stream instead of byte[] in the web service if your file is very large. Probably it will also works with ASMX web service.

ASP.Net Webservice Serialization


I was unable to find a way to return a response in json. I don't think its possible without tinkering with the inner workings. The solution I used was to create an aspx that could handle the file, you could ofcourse use .ashx or WCF as described by OLEG.

0

精彩评论

暂无评论...
验证码 换一张
取 消