簡體   English   中英

為什么相同的POST請求在POSTMAN中起作用,但在瀏覽器AJAX中卻不起作用(找不到404)?

[英]Why the same POST request works in POSTMAN but not in browser AJAX (404 Not Found)?

我已經使用以下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中有效,在POSTMAN中,我因POST請求而得到201。 當我使用以下代碼(由POSTMAN自動生成)將請求移至JavaScript-Jquery-AJAX時。 我收到以下錯誤消息:

{
    "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);
});
// ...

知道為什么會這樣嗎?

似乎您希望該方法成為該控制器上的默認操作,請嘗試將默認操作設置為Index並將您的方法重命名為Index。

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

此問題與錯誤的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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM