加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

.net – 匹配另一条路线的路线,忽略HttpMethodConstraint?

发布时间:2020-12-16 09:59:46 所属栏目:asp.Net 来源:网络整理
导读:我有一个ASP.net MVC 3站点,其中包含以下路由: routes.MapRoute("Get","endpoint/{id}",new { Controller = "Foo",action = "GetFoo" },new { httpMethod = new HttpMethodConstraint("GET") });routes.MapRoute("Post",action = "NewFoo" },new { httpMeth
我有一个ASP.net MVC 3站点,其中包含以下路由:

routes.MapRoute("Get","endpoint/{id}",new { Controller = "Foo",action = "GetFoo" },new { httpMethod = new HttpMethodConstraint("GET") });

routes.MapRoute("Post",action = "NewFoo" },new { httpMethod = new HttpMethodConstraint("POST") });

routes.MapRoute("BadFoo",new { Controller = "Error",action = "MethodNotAllowed" });

routes.MapRoute("NotFound","",new { controller = "Error",action = "NotFound" });

所以在Nutshell中,我有一个匹配某些HTTP谓词的路由,如GET和POST,但是在其他HTTP谓词上,如PUT和DELETE,它应该返回一个特定的错误.

我的默认路线是404.

如果我删除“BadFoo”路由,则针对端点/ {id}的PUT返回404,因为没有其他路由匹配,因此它将转到我的NotFound路由.

问题是,我有很多路线,比如Get和Post,我有一个HttpMethodConstraint,我必须创建一条像BadFoo路线一样的路线,只是为了捕捉路线上的正确匹配而不是方法,这会打击不必要的我的路由.

我如何设置仅使用Get,Post和NotFound路由的路由,同时仍然区分未找到的HTTP 404(=无效的URL)和不允许的HTTP 405方法(=有效的URL,错误的HTTP方法)?

解决方法

您可以使用自定义的ControllerActionInvoker和ActionMethodSelector属性(如[HttpGet],[HttpPost]等)将HTTP方法验证委托给MVC运行时,而不是使用路径约束.

using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication6.Controllers {

   public class HomeController : Controller {

      protected override IActionInvoker CreateActionInvoker() {
         return new CustomActionInvoker();
      }

      [HttpGet]
      public ActionResult Index() {
         return Content("GET");
      }

      [HttpPost]
      public ActionResult Index(string foo) {
         return Content("POST");
      }
   }

   class CustomActionInvoker : ControllerActionInvoker {

      protected override ActionDescriptor FindAction(ControllerContext controllerContext,ControllerDescriptor controllerDescriptor,string actionName) {

         // Find action,use selector attributes
         var action = base.FindAction(controllerContext,controllerDescriptor,actionName);

         if (action == null) {

            // Find action,ignore selector attributes
            var action2 = controllerDescriptor
               .GetCanonicalActions()
               .FirstOrDefault(a => a.ActionName.Equals(actionName,StringComparison.OrdinalIgnoreCase));

            if (action2 != null) {
               // Action found,Method Not Allowed ?
               throw new HttpException(405,"Method Not Allowed");
            }
         }

         return action;
      }
   }
}

请注意我的上一条评论’发现的行动,方法不允许?’,我把它写成一个问题因为可能存在与HTTP方法验证无关的ActionMethodSelector属性…

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读