使用 Ajax 从 Web 服务返回 JSON 而不是 XML,同时'contentType' 'false'



我做了一个Ajax调用,将图像文件发送到我的Web服务之一(.ASMX(方法。一切都可以,但是问题是Web服务返回XML而不是JSON,因为我必须将'contentType'设置为'false',否则无法发送文件。(如果我将contentType设置为application/json; charset=utf-8,它将返回JSON,但我不能这样做,因为我正在发送文件。(

这是我的JavaScript:

function setAvatar(imageFile, successCallback) {
var formData = new FormData();
formData.append("UploadedAvatar", imageFile);
$.ajax({
    type: "POST",
    url: "/Services/UserService.asmx/SetAvatar",
    contentType: false,
    processData: false,
    dataType: 'json',
    data: formData,
    success: function (result) {
        alert(result.d);
        alert(result.d.IsSuccessful);
        if (typeof successCallback === 'function')
            successCallback(result);
    }
});

和Web服务方法:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public Result SetAvatar()
{
    HttpPostedFile postedFile = HttpContext.Current.Request.Files["UploadedAvatar"];
    Image avatar = Image.FromStream(postedFile.InputStream, true, true);
    avatar = new Bitmap(avatar, new Size(150, 150));
    avatar.Save(Path.Combine(path, $"Avatar-Small.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
    return new Result(true, Messages.AvatarSavedSuccessfully);
}

在提出json请求时设置Accept标头

$.ajax({
    type: "POST",
    url: "/Services/UserService.asmx/SetAvatar",
    headers: { //SET ACCEPT HEADER
        Accept : "application/json; charset=utf-8",
    },  
    contentType: false,
    processData: false,
    dataType: 'json',
    data: formData,
    success: function (result) {
        alert(result.d);
        alert(result.d.IsSuccessful);
        if (typeof successCallback === 'function')
            successCallback(result);
    }
});

在服务器端,使用Json.Net可以序列化结果

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SetAvatar() {
    HttpPostedFile postedFile = HttpContext.Current.Request.Files["UploadedAvatar"];
    Image avatar = Image.FromStream(postedFile.InputStream, true, true);
    avatar = new Bitmap(avatar, new Size(150, 150));
    avatar.Save(Path.Combine(path, $"Avatar-Small.jpg"), System.Drawing.Imaging.ImageFormat.Jpeg);
    var result = new Result(true, Messages.AvatarSavedSuccessfully);
    return JsonConvert.SerializeObject(result);
}

这应该允许响应在所需的类型

在将我的头靠在墙上多天后,我终于找出了属于Ajay的解决方案,此处。

虽然没有其他帮助,但我使用了它,它效果很好:

  1. 将方法的返回类型更改为void

  2. ,然后您需要这样做以返回一个值:

    ,而不是在方法中编写return语句。
    Context.Response.ContentType = "application/json; charset=utf-8";
    Context.Response.Write(new JavaScriptSerializer().Serialize(new YourData()));
    
  3. 之后,您可以使用AJAX调用的success事件轻松获得结果:

    success: function (result) {
        alert(result.Property); // Note: Don't use result.d here
    }
    

您需要更新.NET代码并添加options.RespectBrowserAcceptHeader = true

services
    .AddMvc(options => {
        options.RespectBrowserAcceptHeader = true;
    })
    //support application/xml
    .AddXmlDataContractSerializerFormatters()
    //support application/json
    .AddJsonOptions(options => {
        // Force Camel Case to JSON
        options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
    });

dataType: 'json'将自动添加Accept标头

"accept":"application/json, text/javascript, */*; q=0.01"

如果您特别想要application/json,则需要在Ajax选项

中添加以下
headers: {
  Accept : "application/json; charset=utf-8"
}

相关内容

  • 没有找到相关文章

最新更新