Asp.net-Mvc

如何在 ASP.NET MVC 路由中使用帶有 HttpMethodConstraint 的自定義約束?

  • October 28, 2014

我有一個只接受此 URL 上的 POST 的控制器:

POST http://server/stores/123/products

POST 應該是 content-type 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)。

在您的情況下,我認為您想將所有匹配程式碼放在一個巨大的“如果”中:

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;
   }
}

引用自:https://stackoverflow.com/questions/2158782