Routing in ASP.NET Web API

本文探讨了为什么某些操作需要使用HTTP GET方法,并详细解释了ASP.NET WebAPI中的路由机制。介绍了如何通过命名约定或明确指定HTTP属性来选择HTTP方法,以及WebAPI如何使用HTTP动词而非URI路径来选择控制器和操作。

Why is HttpGet required only for some actions?

https://stackoverflow.com/questions/28068868/why-is-httpget-required-only-for-some-actions

Please refer to the post here

You will see that you can use naming convention (which is why the methods with Get in the name work), or you can explicitly specify the HTTP method for an action by decorating the action with the correct HTTP attribute.

Routing in ASP.NET Web API

If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API. This article does not assume any knowledge of ASP.NET MVC.

 

If you self-host Web API, you must set the routing table directly on the HttpSelfHostConfiguration object. For more information, see Self-Host a Web API.

 

The reason for using "api" in the route is to avoid collisions with ASP.NET MVC routing. That way, you can have "/contacts" go to an MVC controller, and "/api/contacts" go to a Web API controller. Of course, if you don't like this convention, you can change the default route table.

 

Once a matching route is found, Web API selects the controller and the action:

  • To find the controller, Web API adds "Controller" to the value of the {controller} variable.
  • To find the action, Web API looks at the HTTP verb, and then looks for an action whose name begins with that HTTP verb name.

           For example, with a GET request, Web API looks for an action prefixed with "Get", such as "GetContact" or "GetAllContacts".

           This convention applies only to GET, POST, PUT, DELETE, HEAD, OPTIONS, and PATCH verbs.

           You can enable other HTTP verbs by using attributes on your controller. We'll see an example of that later.

  • Other placeholder variables in the route template, such as {id}, are mapped to action parameters.

 

 另外,如果route template定义如下,nameaction是自动对应到controller下的方法的。然后controller下的方法,是不需要显式地添加HttpPost的attribute的

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

 

There are two special placeholders: "{controller}" and "{action}".

  • "{controller}" provides the name of the controller.
  • "{action}" provides the name of the action. In Web API, the usual convention is to omit "{action}".

 

转载于:https://www.cnblogs.com/chucklu/p/10283664.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值