为什么相同的POST请求在POSTMAN中有效,但在浏览器AJAX中却没有(404 Not Found)?

时间:2018-01-02 14:50:08

标签: javascript c# jquery ajax asp.net-web-api

我使用以下POST方法创建了ASP.NET WebAPI:

[HttpPost, Route("")]
public IHttpActionResult Post([FromBody] StudentDto student)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    var maxId = conrollerStudents.Max(x => x.ID);
    student.ID = ++maxId;
    conrollerStudents.Add(student);

    InsertStudentIntoDatabase(student);

    return CreatedAtRoute("GetStudent", new { id = student.ID }, student);
}

WebAPI的配置:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.EnableCors();

        config.MapHttpAttributeRoutes();  
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

此API方法仅适用于POSTMAN,因为POST请求得到201。当我使用以下代码将此请求移动到JavaScript-Jquery-AJAX中时(由POSTMAN自动生成)。我收到以下错误消息:

{
    "Message":"No HTTP resource was found that matches the request URI 'http://localhost:59523/api/students'.",
    "MessageDetail":"No action was found on the controller 'Students' that matches the request."
}

这是自动生成的JavaScript-Jquery-AJAX代码,它恰好不起作用:

// ...
var settings = {
    "async": true,
    "crossDomain": true,
    "url": "http://localhost:59523/api/students",
    "method": "POST",
    "headers": {
        "content-type": "application/json"
    },
    "processData": false,
    "data": "{\n  \"FirstName\": \"Sample\",\n  \"LastName\": \"Sample\",\n  \"City\": \"Sample\",\n  \"ListOfCourses\": []\n}"
};

$.ajax(settings).done(function (response) {
    console.log(response);
});
// ...

知道为什么会这样吗?

2 个答案:

答案 0 :(得分:0)

看起来您希望该方法成为该控制器上的默认操作,尝试将默认操作设置为Index并将方法重命名为Index。

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

答案 1 :(得分:0)

此问题与错误的WebAPI配置文件有关: Web.config 。我已将 system.webServer 部分更改为:

<system.webServer>
  <handlers>
    <remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
    <remove name="TRACEVerbHandler"/>
    <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH" modules="IsapiModule" 
          scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />      
    <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH" type="System.Web.Handlers.TransferRequestHandler" 
          preCondition="integratedMode,runtimeVersionv4.0" />
  </handlers>
  <httpProtocol>
    <customHeaders>
      <add name="Access-Control-Allow-Origin" value="*"/>
      <add name="Access-Control-Allow-Headers" value="Content-Type"/>
      <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS"/>
    </customHeaders>
  </httpProtocol>
</system.webServer>