使用Web API上传时不支持的媒体类型 [英] Unsupported media type when uploading using web api

查看:641
本文介绍了使用Web API上传时不支持的媒体类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在迁移服务从MVC利用asp.net网页API。
我有这样的 ApiController

I am currently migrating a service to utilise asp.net web api from mvc. I have this ApiController

[Authorize]
public class UploadController : ApiController
{
    private readonly ObjectService service;
    private readonly string companyId;

    public UploadController()
    {
        this.companyId = "D49AA22B-3476-4FAC-8BEF-38F53F9378F3";
        this.service = new ObjectService(ConfigurationManager.AppSettings["AWSAccessKey"], ConfigurationManager.AppSettings["AWSSecretKey"], this.companyId);
    }

    // POST api/upload/5
    [HttpPost]
    [Route("api/upload")]
    public IHttpActionResult StartUpload(UploadModel model)
    {
        try
        {
            var id = Guid.NewGuid().ToString();

            if (!service.Exists(model.File.FileName))
            {
                service.Add(id);

                var stream = new MemoryStream();
                var caller = new AsyncMethodCaller(service.Upload);

                model.File.InputStream.CopyTo(stream);

                var result = caller.BeginInvoke(id, stream, model.File.FileName, new AsyncCallback(CompleteUpload), caller);
            }
            else
                throw new Exception("This file already exists. If you wish to replace the asset, please edit it.");

            return Ok(id);
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    public void CompleteUpload(IAsyncResult result)
    {
        var caller = (AsyncMethodCaller)result.AsyncState;
        var id = caller.EndInvoke(result);

        //this.service.Remove(id);
    }

    // GET api/upload/progress/5
    [HttpGet]
    [Route("api/upload/progress/{id}")]
    public IHttpActionResult GetCurrentProgress(string id)
    {
        try
        {
            var progress = service.GetStatus(id);
            return Ok(progress);
        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }
    }

    protected override void Dispose(bool disposing)
    {
        if (disposing)
            this.service.Dispose();

        base.Dispose(disposing);
    }
}

正如你可以看到,如果我做一个职位为 API /上传应开始上传我的文件。
这些方法已经从现有的MVC控制器转换(这回的 JsonResult 而不是 IHttpActionResult

As you can see, if I do a post to api/upload it should start to upload my file. These methods have been converted from an existing mvc Controller (which returned JsonResult instead of IHttpActionResult)

我的 UploadModel 是这样的:

public class UploadModel
{
    public HttpPostedFileBase File { get; set; }
    public string FileName { get; set; }
}

和我的jQuery是这样的:

and my jquery looks like this:

function uploadFile() {
    var file = $("#File")[0].files[0];

    if (file) {
        var fileName = "test/" + $('input[type=file]').val().split('\\').pop();
        var data = new FormData();

        data.append("File", file);
        data.append("FileName", fileName);

        $.ajax({
            url: "/Api/Upload",
            type: 'POST',
            data: data,
            contentType: false,
            processData: false,
            success: function (data) {
                console.log("uploading");
                console.log(data);

                createCategory(fileName);
            },
            error: function () {
                displayAlert(".message", "There was a problem when uploading the file!", "danger");
            }
        });
    } else {
        createCategory();
    }
};

当我运行这个code,我得到的错误

When I run this code, I get the error

HTTP://r3plica.localhost:3892 /原料药/上传的415(不支持的媒体型)

POST http://r3plica.localhost:3892/Api/Upload 415 (Unsupported Media Type)

但如果我注释掉行的contentType:假的,并运行我的脚本,我得到一个错误的请求,虽然我的断点被击中,在 UploadModel 实际上是空。

but if I comment out the line contentType: false, and run my script I get a bad request, although my breakpoints get hit, the UploadModel is actually null.

任何人都可以提出一个解决方案?

Can anyone suggest a solution?

干杯,

/ r3plica

/r3plica

推荐答案

尝试添加数据类型:JSON,如果您认为该服务返回JSON
并替换你的Ajax调用下面的错误HANDELING函数来获得更好的理解问题,你所面对的类型

Try adding dataType: 'json', if you think the service is returning JSON and replace the following error handeling function in your ajax call to get a better understanding of the type of problem you are facing

   error: function(xhr, exception) {
       if (xhr.status === 0) {
       alert('Not connected. Verify Login details or Network.');
       } else if (xhr.status == 401) {
       alert('Invalid Username or Password');
       } else if (xhr.status == 404) {
       alert('Requested page not found. [404]');
       } else if (xhr.status == 500) {
       alert('Internal Server Error [500].');
       } else if (exception === 'parsererror') {
       alert('Requested JSON parse failed.');
       } else if (exception === 'timeout') {
       alert('Time out error.');
       } else if (exception === 'abort') {
       alert('Ajax request aborted.');
       } else {
       alert('Uncaught Error.\n' + xhr.responseText);
       }
       }

注释掉的内容类型

comment out the content Type

这篇关于使用Web API上传时不支持的媒体类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆