是否可以在 ASP.NET MVC 中实现 X-HTTP-Method-Override? [英] Is it possible to implement X-HTTP-Method-Override in ASP.NET MVC?

查看:14
本文介绍了是否可以在 ASP.NET MVC 中实现 X-HTTP-Method-Override?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ASP.NET MVC 实现一个 RESTful API 的原型,除了这里和那里的奇怪错误之外,我已经实现了我在开始时提出的所有要求,除了调用者能够使用 X-HTTP-Method-Override自定义标头覆盖HTTP方法.

I'm implementing a prototype of a RESTful API using ASP.NET MVC and apart from the odd bug here and there I've achieve all the requirements I set out at the start, apart from callers being able to use the X-HTTP-Method-Override custom header to override the HTTP method.

我想要的是以下请求...

What I'd like is that the following request...

GET /someresource/123 HTTP/1.1
X-HTTP-Method-Override: DELETE

...将被分派到实现 DELETE 功能而不是该操作的 GET 功能的控制器方法(假设有多个方法实现该操作,并且它们用不同的 [AcceptVerbs] 属性标记).因此,鉴于以下两种方法,我希望将上述请求分派给第二种方法:

...would be dispatched to my controller method that implements the DELETE functionality rather than the GET functionality for that action (assuming that there are multiple methods implementing the action, and that they are marked with different [AcceptVerbs] attributes). So, given the following two methods, I would like the above request to be dispatched to the second one:

[ActionName("someresource")]
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetSomeResource(int id) { /* ... */ }

[ActionName("someresource")]
[AcceptVerbs(HttpVerbs.Delete)]
public ActionResult DeleteSomeResource(int id) { /* ... */ }

有人知道这是否可能吗?这样做需要做多少工作......?

Does anybody know if this is possible? And how much work would it be to do so...?

推荐答案

您将无法按原样使用 [AcceptVerbs] 属性,因为它与请求的实际 HTTP 动词相关联.幸运的是 [AcceptVerbs] 属性非常简单;您可以在 http://www.codeplex.com/aspnet/SourceControl/changeset/view/21528#266431.

You won't be able to use the [AcceptVerbs] attribute as-is since it's tied to the request's actual HTTP verb. Fortunately the [AcceptVerbs] attribute is very simple; you can see the source for yourself at http://www.codeplex.com/aspnet/SourceControl/changeset/view/21528#266431.

简而言之,子类 AcceptsVerbsAttribute 并覆盖 IsValidForRequest() 方法.实现将类似于以下内容:

In short, subclass AcceptsVerbsAttribute and override the IsValidForRequest() method. The implementation would be something like the following:

string incomingVerb = controllerContext.HttpContext.Request.Headers["X-HTTP-Method-Override"] ?? controllerContext.HttpContext.Request.Method;
return Verbs.Contains(incomingVerb, StringComparer.OrdinalIgnoreCase);

这篇关于是否可以在 ASP.NET MVC 中实现 X-HTTP-Method-Override?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆