ASP.NET MVC AcceptVerbs and registering routes

我与影子孤独终老i 提交于 2019-11-27 03:06:56

问题


do I have to register the HttpVerb constraint in my route definition (when i'm registering routes) if i have decorated my action method with the [AcceptVerbs(..)] attribute already?

eg. i have this.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection formCollection)
{ .. }

do i need to add this to the route that refers to this action, as a constraint?


回答1:


The difference between the two is the following: Let's assume the Create method in question is on the HomeController.

Using the AcceptVerbs attribute does not affect routing. It's actually something used by the action invoker. What it allows you to do is have 2 action methods on a controller with the same name that each respond to a different HTTP Method.

public ActionResult Create(int id) { .. }

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection formCollection) { .. }

So when a request for /home/create comes in, the route will match and hand off the request to the controller's invoker. The invoker then invokes the correct method by looking at the AcceptVerbs attribute.

Using the HttpMethodConstraint in routing will make it such that the route itself will not match the request. So when a POST request comes in for /home/create, neither action method will be called because that route will not match the request. It's possible that another route will match that request though.

Part of the reason for the overlap here is that Routing is a feature of ASP.NET 3.5 SP1 and isn't specific to MVC. MVC uses Routing, but Routing is also used by Dynamic Data and we plan to integrate routing with ASP.NET Web Forms.




回答2:


Nope -- Create will only respond to POST requests.

You can have other implementations of Create with different AcceptVerb attributes, or one with no attribute that will catch all other requests.

If that was your only Create method, any GET (or other non-POST) request would result in a 404.

I assume under the hood this is all being done by the routing engine anyways. [edit: nope, see Haacked's post]




回答3:


First decorate like this:

[ActionName("ItemEdit"), AcceptVerbs(HttpVerbs.Post)]
public virtual object ItemSave(Menu sampleInput)

then you need to add route like this:

 AddRoute(
                "SampleEdit",
                "Admin/{sampleID}/Edit",
                new { controller = "Sample", action = "ItemEdit", validateAntiForgeryToken = true },
                new { areaID = new IsGuid() },
                new { Namespaces = controllerNamespaces }
           );


来源:https://stackoverflow.com/questions/283209/asp-net-mvc-acceptverbs-and-registering-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!