当Postman请求时,httppostedfilebase在Web API中接收null

时间:2018-02-16 09:56:45

标签: asp.net-web-api postman httppostedfilebase

我试图向我的API控制器发送一个帖子请求。它接收除文件输入之外的所有输入。我尝试了一些解决方案但没有任何工作。我在MVC中创建了相同的表单并且它可以工作,但是我没有在API中工作。

我的Blogger控制器/创建操作

public HttpResponseMessage Create(Blogger objBlogger)
{

}

我的Blogger模型

public class Blogger
{
    public string Blogger_Id { get; set; }
    [Required]
    public string BloggerName { get; set; }
    [Required]
    public string BloggerUserName { get; set; }
    [Required]
    [RegularExpression(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$")]
    public string BloggerEmail { get; set; }
    [Required]
    [RegularExpression("^[0-9]*$")]
    public string BloggerMobileNumber { get; set; }
    public string BloggerProfilePicture { get; set; }
    [Required]
    public string BloggerPassword { get; set; }
    public HttpPostedFileBase UploadProfilePicture { get; set; }
}

我的邮递员代码

POST /api/Blogger/Create HTTP/1.1
Host: localhost:3694
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Type: application/json
Cache-Control: no-cache
Postman-Token: 8097929a-bc93-42a4-8bc8-0e9ea98a279e

------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="BloggerName"

DemoName
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="BloggerUserName"

DemoUserName
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="BloggerEmail"

DemoEmail@gmail.com
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="BloggerMobileNumber"

9999999999
------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="UploadProfilePicture"; filename="asset.JPG"
Content-Type: image/jpeg


------WebKitFormBoundary7MA4YWxkTrZu0gW
Content-Disposition: form-data; name="BloggerPassword"

DemoPassword
------WebKitFormBoundary7MA4YWxkTrZu0gW--

1 个答案:

答案 0 :(得分:0)

对于Web API,请使用以下内容:

[HttpPost]
public async Task<HttpResponseMessage> Create()
{
    if (!Request.Content.IsMimeMultipartContent())
    {
        this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
    }

    string root = HttpContext.Current.Server.MapPath("~/temp");
    var provider = new MultipartFormDataStreamProvider(root);
    var result = await Request.Content.ReadAsMultipartAsync(provider);

    // Files
    foreach (MultipartFileData file in provider.FileData)
    {
        Debug.WriteLine(file.Headers.ContentDisposition.FileName);
        Debug.WriteLine("File path: " + file.LocalFileName);
    }

    // Form data
    foreach (var key in provider.FormData.AllKeys)
    {
        foreach (var val in provider.FormData.GetValues(key))
        {
            // your Blogger obj
            ...
        }
    }
    ...
}