微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 使用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);
}

这应该允许响应处于所需类型

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐