gpt4 book ai didi

c# - HTTP 属性与路由相同 - ASP.Net Core API?

转载 作者:行者123 更新时间:2023-11-30 23:02:26 24 4
gpt4 key购买 nike

我正在制作一个 ASP.net core 2.0 Web API 并且在我的 Controller 中有一个方法叫做

[HttpPost("Create")]
public void Create()
{
// var d = employee;
}

HttpPost 是否与 [Route] 属性相同,还是我需要两者?

最佳答案

对于 Asp.Net Core Web API,您不需要两者。

它的作用与 Route 相同,是推荐的方法。将 MVC 与 View 一起使用时,您可以同时使用 RouteHttp{Verb}

文档状态...

When building a REST API, it's rare that you will want to use [Route(...)] on an action method. It's better to use the more specific Http*Verb*Attributes to be precise about what your API supports. Clients of REST APIs are expected to know what paths and HTTP verbs map to specific logical operations.

引用 Routing to Controller Actions in ASP.NET Core

我还建议让您的操作返回 IActionResult 以允许从操作返回正确的 HTTP 动词。

[HttpPost("Create")]
public IActionResult Create() {
// var d = employee;
return Ok();
}

void 操作总是返回 200 OK 除非抛出异常。这限制了操作的可能响应。

关于c# - HTTP 属性与路由相同 - ASP.Net Core API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50477553/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com