通过邮递员发送JSON +文件

时间:2020-11-06 13:47:09

标签: c# asp.net asp.net-web-api asp.net-core-webapi multipartform-data

我有一个Android应用程序,该程序将以下多部分内容发布到我的应用程序中。该请求包含JSON以及图像文件。

        AndroidNetworking.upload(baseUrl+"updateuserprofile")
            .addMultipartFile("UserImage",userImage)
            .setTag("UserImage")
            .addMultipartParameter("PhoneNumber",phone)
            .addMultipartParameter("UserId",userId)
            .addMultipartParameter("firstName",firstName)
            .addMultipartParameter("LastName",lastName)
            .setPriority(Priority.HIGH)
            .setOkHttpClient(okHttpClient)
            .build();

我的应用程序是ASP .NET WebAPI 2.0应用程序,我无法弄清楚如何将EditProfile参数始终显示为NULL

public async Task<IHttpActionResult> EditProfile ([FromBody] EditProfile profile)
{
    // `profile` is populated if only JSON is sent.
    // `profile` is `NULL` if multi-part content is sent.
}

public class EditProfile
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string MobileNo { get; set; }
    public long UserId { get; set; }
    public string ImageString { get; set; }
    public HttpPostedFileBase PostedFile { get; set; }
}

任何建议将不胜感激。

1 个答案:

答案 0 :(得分:0)

您要发送的是多部分内容,它不是json,而是表单数据。因此,您应该使用[FromBody]而不是使用[FromFrom]。 ([FromForm]是ASP.Net Core的一项功能,因为您正在使用完整框架,因此它对您不起作用)

public async Task<IHttpActionResult> EditProfile ([FromForm] EditProfile profile)
{
    // `profile` will not be populated if JSON is sent.
    // `profile` will be populated if multi-part content is sent.
}

public class EditProfile
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string MobileNo { get; set; }
    public long UserId { get; set; }
    public string ImageString { get; set; }
    public HttpPostedFileBase PostedFile { get; set; }
}

我相信ASP.Net Web API(完整框架)不允许您将HttpPostedFile添加为模型的一部分。如果您发现任何类似PostedFile的问题,例如null。删除HttpPostedFile作为操作的参数。

并且如果您需要接受不带文件的Json请求以及带文件的多部分表单数据。您应该从参数中删除[FromForm],然后让框架为您处理。

public async Task<IHttpActionResult> EditProfile (EditProfile profile, HttpPostedFileBase postedFile)
{
    // `profile` should be populated with a JSON or multi-part content
    // `postedFile` will be  populated only if multi-part content is sent with a file.
}

public class EditProfile
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public string MobileNo { get; set; }
    public long UserId { get; set; }
    public string ImageString { get; set; }
    // REMOVE HttpPostedFileBase property
}
相关问题