简体   繁体   English

.Net Core 2.2 Web API 405

[英].Net Core 2.2 Web API 405

I am trying to setup a .net core 2.2 web api to use a post verb. 我正在尝试设置.net core 2.2 web api以使用后置动词。 Anything other than a get verb returns a 405 no matter if it is run on my local machine (w10 iis eXPRESS 10.0) or the windows server (2016 R2 IIS 8.0). 除了get动词之外的任何内容都返回405,无论它是在我的本地计算机(w10 iis eXPRESS 10.0)还是Windows服务器(2016 R2 IIS 8.0)上运行。 I've read the other posts about disabling WebDav in your config file, adding a route, and completely removing the WebDav feature. 我已经阅读了有关在配置文件中禁用WebDav,添加路由以及完全删除WebDav功能的其他帖子。 I have done all of those to no avail. 我做了所有这些都无济于事。 I'm just starting to develop in core and find this baffling, on the same server is a non-core web api that runs on .net framework 4.5 that processes GET,PUT,POST,DELETE without error. 我刚刚开始在核心开发并发现这个令人费解,在同一台服务器上是一个非核心的web api,运行在.net framework 4.5上,可以无错误地处理GET,PUT,POST,DELETE。 And yes, I have restarted the server after making changes to any of the configurations. 是的,我在更改任何配置后重新启动了服务器。 The following are the web.config changes that I made, the last one coming directly from MS. 以下是我所做的web.config更改,最后一个直接来自MS。 Basic project that reproduces the same error on my machine and server is here https://github.com/FranciscanMedia/error405_core/tree/master it is just a standard web api project you get when you fire up VS2019. 在我的机器和服务器上重现相同错误的基本项目在这里https://github.com/FranciscanMedia/error405_core/tree/master它只是你启动VS2019时获得的标准web api项目。

<system.webServer>    
    <handlers accessPolicy="Read, Script">
       <remove name="WebDAV" />
       <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
       <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"
          path="*."
          verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
          modules="IsapiModule"
          scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
          preCondition="classicMode,runtimeVersionv4.0,bitness64"
          responseBufferLimit="0" />
    </handlers>
</system.webServer>
<system.webServer>    
    <modules>        
        <remove name="WebDAVModule" />    
    </modules>    
    <handlers>        
        <remove name="WebDAV" />    
    </handlers>
</system.webServer>
<system.webServer>
    <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="false">
        <remove name="WebDAVModule"/>
    </modules>    
</system.webServer>
<system.webServer>
    <handlers accessPolicy="Read, Script">
        <remove name="WebDAV" />
        <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
        <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit"
           path="*."
           verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
           modules="IsapiModule"
           scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll"
           preCondition="classicMode,runtimeVersionv4.0,bitness64"
           responseBufferLimit="0" />
    </handlers>
</system.webServer>

Short answer 简短的回答

It could be as simple as that. 它可以这么简单。 The reason is routing. 原因是路由。

Just send your POST request to right URL like https://localhost:44327/api/values/123 . 只需将您的POST请求发送到正确的URL,如https://localhost:44327/api/values/123

POST请求更正和错误的端点


Detailed explanation 详细解释

It's not the issue. 这不是问题。 It works as expected. 它按预期工作。

You make a GET request to https://localhost:44327/api/values/ . 您向https://localhost:44327/api/values/发出GET请求。 It returns 200 OK . 它返回200 OK

But when you make a POST request to the same URL https://localhost:44327/api/values/ . 但是当您向同一个URL发出POST请求时, https://localhost:44327/api/values/ It says 405 Method not allowed . 它说405 Method not allowed

However, you get 405 . 但是,你得到405 It is happening because you are hitting the GET endpoint with POST method. 它正在发生,因为您正在使用POST方法访问GET端点。

Microsoft Docs says: Microsoft Docs说:

... the HTTP client sent a valid JSON request to the URL for a Web API application on a web server, but the server returned an HTTP 405 error message which indicates that the PUT method was not allowed for the URL. ... HTTP客户端向Web服务器上的Web API应用程序的URL发送了有效的JSON请求,但服务器返回了HTTP 405错误消息,表明不允许对该URL使用PUT方法。 In contrast, if the request URI did not match a route for the Web API application, the server would return an HTTP 404 Not Found error. 相反,如果请求URI与Web API应用程序的路由不匹配,则服务器将返回HTTP 404 Not Found错误。

https://docs.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications https://docs.microsoft.com/en-us/aspnet/web-api/overview/testing-and-debugging/troubleshooting-http-405-errors-after-publishing-web-api-applications

If you simply remove the GET endpoint. 如果您只是删除GET端点。 The POST request will start returning 404 Not found . POST请求将开始返回404 Not found Which means that you are not hitting any registered route. 这意味着您没有达到任何注册路线。

To send POST request you need to use different URL according to the routing rules. 要发送POST请求,您需要根据路由规则使用不同的URL。

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{

    // POST api/values
    [HttpPost("{val}")]
    public StatusCodeResult Post()
    {
        return Ok();
    }
}

This attribute-based configuration means that route of your POST endpoint is /api/Values/{val} . 这种基于属性的配置意味着POST端点的路由是/api/Values/{val} Where {val} is any value. 其中{val}是任何值。 It's not processed in the endpoint. 它不在端点中处理。

If you want to process it, you should pass it to the method: 如果要处理它,则应将其传递给方法:

[HttpPost("{val}")]
public StatusCodeResult Post(string val)
{
    return Ok();
}

I think that in your controller you have to import another library. 我认为在你的控制器中你必须导入另一个库。 Try 尝试

using System.Web.Http;

Instead of 代替

using Microsoft.AspNetCore.Mvc

Looking at what you have defined: 看看你定义的内容:

[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase

Then for the action: 然后为行动:

[HttpPost("{val}")]
public StatusCodeResult Post()
{
        return Ok();
}

Your routing matches the following url: 您的路由符合以下网址:

https://localhost:44327/api/values/StatusCodeResult HTTPS://本地主机:44327 / API /值/ StatusCodeResult

It is going to take your main route defined on your controller [Route("api/[controller]")] 它将在您的控制器[Route(“api / [controller]”)上定义您的主路径]

Then you are defining the "template" to use "{val}" 然后你定义“模板”使用“{val}”

This is telling it to use the ActionResult specific name and to expect var val to be passed/appened. 这告诉它使用ActionResult 特定名称并期望传递/附加var val。

Checking out the official documentation here: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.2 在这里查看官方文档: https//docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-2.2

under section "Token replacement in route templates ([controller], [action], [area])" 在“路径模板中的令牌替换([控制器],[操作],[区域])”部分下

They specifiy: 他们指定:

For convenience, attribute routes support token replacement by enclosing a token in square-braces ([, ]). 为方便起见,属性路由通过将标记括在方括号([,])中来支持令牌替换。 The tokens [action], [area], and [controller] are replaced with the values of the action name, area name, and controller name from the action where the route is defined. 标记[action],[area]和[controller]将替换为定义路径的操作中的操作名称,区域名称和控制器名称的值。 In the following example, the actions match URL paths as described in the comments: 在以下示例中,操作匹配URL路径,如注释中所述:

[Route("[controller]/[action]")]
public class ProductsController : Controller
{
  [HttpGet] // Matches '/Products/List'
  public IActionResult List() {
    // ...
  }

  [HttpGet("{id}")] // Matches '/Products/Edit/{id}'
  public IActionResult Edit(int id) {
    // ...
  }
}

If you want it to just route based on just verbs (follow a pattern where each api endpoint just handles operations for that specific object) then you would change your post method to just 如果你想让它只基于动词进行路由(遵循每个api端点只处理该特定对象操作的模式),那么你可以将你的post方法更改为just

    [HttpPost]
    public ActionResult Post(string val)
    {
        return Ok();
    }

I totally agree with @Vladimir's answer. 我完全赞同@ Vladimir的回答。 I dont have enough points to add comments to the answer by @vlaimir so i am adding my thoughts and suggestions. 我没有足够的积分来为@vlaimir的答案添加评论,所以我添加了我的想法和建议。

The code you have on your github, 您在github上的代码,

// POST api/values
[HttpPost("{val}")]
public StatusCodeResult Post()
{
     return Ok();
}

This is a post and it would expect a value {val} per the route action configuration. 这是一个帖子,它会期望路由操作配置的值为{val}。 Since you may try to hit the post without any value, thats not permitted. 既然你可能试图在没有任何价值的情况下发帖,那是不允许的。 Ensure you supply some value and then do the POST. 确保提供一些值,然后执行POST。 If you are using POSTMAN, you may have to supply the BODY of your request with some value. 如果您使用的是POSTMAN,则可能需要为您的请求的BODY提供一些值。 Swagger is a great util tool to embed into the web api's and that comes with excellent intuitive UI for our routes/resources. Swagger是一个很好的工具,可嵌入到web api中,并为我们的路径/资源提供出色的直观UI。 That might be even ideal to help determine and ensure you supply the right value. 这可能是帮助确定并确保您提供正确价值的理想选择。

Otherwise, you dont need to modify or worry about your IIS or IIS Express settings. 否则,您无需修改​​或担心IIS或IIS Express设置。 or webdav. 或webdav。

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

相关问题 .Net Core 2.2 Web API路由 - .Net Core 2.2 Web API Routing 在 .NET Core 2.2 中嵌套资源 Web API - Nesting resources in .NET Core 2.2 Web API Net Core Web API 2.2 保护敏感数据 - Net Core Web API 2.2 Protecting sensitive data 不允许使用ASP.NET Core 2.2 WebAPI 405方法 - ASP.NET Core 2.2 WebAPI 405 Method Not Allowed 如何将 .NET Core 2.2 Web API 迁移到 Z303CB0EF9EDB9082D61BBBE5825D70? - How do I migrate .NET Core 2.2 Web API to .NET Core 3.0? 在发布对象数组时收到来自 Web API 的 405 HTTP 响应(.Net Core 5) - Receiving a 405 HTTP Response from Web API when posting an array of objects (.Net Core 5) 在asp net core web api中上传文件时,有没有办法避免http错误405? - Is there a way to avoid http error 405 when uploading a file in asp net core web api? ASP.NET Core 3.1 Web API post 方法导致 405“Method Not Allowed”错误 - ASP.NET Core 3.1 Web API post method causing 405 "Method Not Allowed" error 方法不允许 405 POST ASP.NET CORE 5.0 WEB API - Method not allowed 405 POST ASP.NET CORE 5.0 WEB API ASP.NET Core 5.0 Web API 在尝试使用 HttpDelete 删除记录时抛出错误 405 - ASP.NET Core 5.0 Web API throws error 405 when trying to delete record using HttpDelete
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM