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

asp.net-mvc – 如何在ASP.NET MVC路由中使用带有HttpMethodCons

发布时间:2020-12-15 22:16:55 所属栏目:asp.Net 来源:网络整理
导读:我有一个控制器只接受此URL上的POST: POST http://server/stores/123/products POST应该是内容类型的application / json,所以这就是我在路由表中的内容: routes.MapRoute(null,"stores/{storeId}/products",new { controller = "Store",action = "Save" },
我有一个控制器只接受此URL上的POST:
POST http://server/stores/123/products

POST应该是内容类型的application / json,所以这就是我在路由表中的内容:

routes.MapRoute(null,"stores/{storeId}/products",new { controller = "Store",action = "Save" },new {
                      httpMethod = new HttpMethodConstraint("POST"),json = new JsonConstraint()
                    }
               );

JsonConstraint的位置是:

public class JsonConstraint : IRouteConstraint
{
    public bool Match(HttpContextBase httpContext,Route route,string parameterName,RouteValueDictionary values,RouteDirection routeDirection)
    {
        return httpContext.Request.ContentType == "application/json";
    }
}

当我使用这条路线时,我得到了一个405 Forbidden:

不允许使用用于访问路径’/ stores / 123 / products’的HTTP谓词POST

但是,如果我删除json = new JsonConstraint()约束,它可以正常工作.有人知道我做错了什么吗?

解决方法

我把它放在评论中,但没有足够的空间.

编写自定义约束时,检查routeDirection参数并确保逻辑仅在正确的时间运行非常重要.

该参数告诉您在处理传入请求时是运行约束还是在某人生成URL时运行约束(例如当他们调用Html.ActionLink时).

在你的情况下,我认为你想把所有匹配的代码放在一个巨大的“if”中:

public bool Match(HttpContextBase httpContext,RouteDirection routeDirection) 
{
    if (routeDirection == RouteDirection.IncomingRequest) {
        // Only check the content type for incoming requests
        return httpContext.Request.ContentType == mimeType; 
    }
    else {
        // Always match when generating URLs
        return true;
    }
}

(编辑:李大同)

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

    推荐文章
      热点阅读