gpt4 book ai didi

asp.net-mvc - 如何在 ASP.NET MVC 路由中使用带有 HttpMethodConstraint 的自定义约束?

转载 作者:行者123 更新时间:2023-12-04 06:28:55 25 4
gpt4 key购买 nike

我有一个仅接受此 URL 上的 POST 的 Controller :

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:
The HTTP verb POST used to access path '/stores/123/products' is not allowed
但是,如果我删除 json = new JsonConstraint()约束,它工作正常。有谁知道我做错了什么?

最佳答案

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

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

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

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

public bool Match(HttpContextBase httpContext, Route route,
string parameterName, RouteValueDictionary values,
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;
}
}

关于asp.net-mvc - 如何在 ASP.NET MVC 路由中使用带有 HttpMethodConstraint 的自定义约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2158782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com