繁体   English   中英

Ajax调用在JQuery中提供了不受支持的媒体类型,但在MVC中却没有

[英]Ajax call gives Unsupported Media Type in JQuery, but not in MVC

我正在尝试通过网络api提交包含文件的表单。 每当我尝试发送它时, ajax调用都会给我一个错误:

jqXHR:[对象对象]

textStatus:错误

errorThrow:不支持的媒体类型

在后端时,我得到了我的MVC ,它没有给我该错误(不支持的媒体类型):

if (!Request.Content.IsMimeMultipartContent()) //gives false
{
    //415
    return Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}

这是我的Jquery代码:

$(function () {
    $('#btnSubmit').on('click', function (event) {
        if (isValidJobForm()) {
            console.log('the form is valid');
            processSolicit();
            $(this).closest('form').submit();
        }
    });
});

function processSolicit() {
    var $form = $('#frmApplication');
    $.ajax({
        type: "POST",
        url: "http://consulthrtest.eu/api/register/registercandidate",
        contentType: false,
        processData: false,
        data: $form.serialize(),
        success: function (serverResponse) {
            alert('application service called');
            if (serverResponse.d == 'false') {
                console.log('server unable to process');
            } else {
                notification("Uw sollicitatie is ingezonden!");
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("application failed");
            alert('Inzenden solicitatie mislukt! Probeer nogmaals.' + '\njqXHR: ' + jqXHR + '\ntextStatus: ' + textStatus + '\nerrorThrow: ' + errorThrown);
        }
    }).done(function (result) {
        alert(result.d);
        clearForms($form);
    });
}

这是我的MVC代码

public async Task<HttpResponseMessage> RegisterCandidate()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            //415
            return Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
        }

        var provider = new MultipartMemoryStreamProvider();

        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            int vacancyTranslationId = 0;
            byte[] fileContent = {};
            string fileName = null;
            string motivation = null;
            ContactDto newContact = new ContactDto();

            foreach (var content in provider.Contents)
            {
                if(content.Headers.ContentDisposition.FileName == null)
                {
                    //handle regular input field
                    switch (content.Headers.ContentDisposition.Name.Replace("\"",string.Empty))
                    {
                        case("firstName"):
                        {
                            newContact.FirstName = content.ReadAsStringAsync().Result;
                            break;
                        }
                        case ("lastName"):
                        {
                            newContact.LastName = content.ReadAsStringAsync().Result;
                            break;
                        }
                        case ("email"):
                        {
                            newContact.Email = content.ReadAsStringAsync().Result;
                            break;
                        }
                        case ("phone"):
                        {
                            newContact.PrimaryPhone = content.ReadAsStringAsync().Result;
                            break;
                        }
                        case ("motivation"):
                        {
                            motivation = content.ReadAsStringAsync().Result;
                            break;
                        }
                        case("vacancyTranslationId"):
                        {
                            vacancyTranslationId = int.Parse(content.ReadAsStringAsync().Result);
                            break;
                        }
                    }
                }
                else
                {
                    //handle uploaded file
                    fileContent = content.ReadAsByteArrayAsync().Result;
                    fileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
                }
            }

            if (string.IsNullOrEmpty(newContact.FirstName) ||
                string.IsNullOrEmpty(newContact.LastName) ||
                string.IsNullOrEmpty(newContact.Email) ||
                string.IsNullOrEmpty(newContact.PrimaryPhone) ||
                string.IsNullOrEmpty(motivation) ||
                vacancyTranslationId == 0 ||
                fileContent.Length == 0)
            {
                //406
                return Request.CreateResponse(HttpStatusCode.NotAcceptable);
            }

            var result =_registerContactCommandHandler.Execute(new RegisterContactCommand(newContact, fileName, fileContent , vacancyTranslationId, motivation));

            if (result.HasError)
            {
                //409
                return Request.CreateResponse(HttpStatusCode.Conflict);
            }

            //201
            return Request.CreateResponse(HttpStatusCode.Created);
        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

这是HTML表单:

<form runat="server" id="frmApplication" action="http://consulthrtest.allphi.eu/api/register/registercandidate" method="post" name="frmApplication" role="form" enctype="multipart/form-data">
    <div class="row clearfix">
        <asp:HiddenField runat="server" ID="vacancyId" Value="" />
        <input type="hidden" name="vacancyTranslationId" value="7" />
        <div class="col-sm-6 column form-column">
            <label for="firstName" class="sr-only">Voornaam</label>
            <input runat="server" id="firstName" name="firstName" type="text" class="form-control input-lg" placeholder="Voornaam" />
        </div>
        <div class="col-sm-6 column form-column">
            <label for="lastName" class="sr-only">Achternaam</label>
            <input runat="server" id="lastName" name="lastName" class="form-control input-lg" type="text" placeholder="Achternaam" />
        </div>
        <div class="col-md-12 column form-column">
            <label for="email" class="sr-only">Email</label>
            <input runat="server" id="email" name="email" class="form-control input-lg" type="text" placeholder="Email" />
        </div>
        <div class="col-md-12 column form-column">
            <label for="phone" class="sr-only">Telefoon</label>
            <input runat="server" id="phone" name="phone" class="form-control input-lg" type="text" placeholder="Telefoonnummer" />
        </div>
    </div>
    <div class="col-sm-6 column">
        <label for="motivation" class="sr-only">Motivatie</label>
        <textarea runat="server" id="motivation" name="motivation" class="form-control input-lg" rows="7" placeholder="Motivatie"></textarea>
    </div> 
    <span class="input-group-btn">
        <asp:FileUpload runat="server" ID="cv" />
        <input runat="server" type="text" name="cv" id="fileTextField" class="form-control input-lg" placeholder="Selecteer uw CV" readonly="true" />
        <div class="col-sm-6 column">
            <input id="btnSubmit" type="button" value="Solliciteren" class="btn btn-primary btn-lg pull-right" />
        </div>
    </span>
</form>

这在使用SpringMVC @ResponseBody时发生在我身上,是因为没有在请求中设置accept标头。 @RequestBody使用“ Content-Type”标头来查找来自客户端的数据格式。 @ResponseBody使用“ accept”标头来确定将日期发送回客户端的格式。 因此,在请求中同时设置两者将清除不支持的媒体类型的错误

 $('#submit').click(function(){ console.log("submiting"); data={ submitBy:$('#name').val() , subject: $('#subject').val() }; $.ajax({ headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, 'type': 'POST', 'url': '/my/ajax/url', 'data': JSON.stringify(data), 'dataType': 'json', 'success': function(data, status){ alert("Data: " + data + "\\nStatus: " + status); } }); }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM