2016-03-08 42 views
2

我想用屬性路由到URL參數綁定到我的Point對象和屬性[FromUri]使得下列URL是可能的:傳遞複雜對象的ASP.NET Web API使用FromUri

/富-1 ,2

public IHttpActionResult PostFoo(
    [FromBody] string content, 
    [FromUri] Point point) 
{ 
} 

public class Point 
{ 
    public int A { get; set; } 
    public int B { get; set; } 

    // ...Other properties omitted for simplicity 
} 

我曾嘗試以下路由屬性但這些工作:

[Route("foo-{a},{b}")] 
[Route("foo-{A},{B}")] 
[Route("foo-{point.A},{point.B}")] 

請注意,我無法使用查詢字符串參數,因爲嚴重構建的第三方服務不會在其URL中接受&符號(是的,那很糟糕)。所以我試圖建立所有的查詢字符串參數到URL本身。

+0

你可能要考慮使用的URL,重寫重寫URL這使它對MVC之前。將使任何網址可笑的容易。 –

+0

@ErikPhilips我正在考慮寫一些過濾器或模型活頁夾來做同樣的事情。我想回到IIS是一個有效的選擇。 –

+1

模型綁定器在選擇路由的過程中很晚。你可能需要寫一個[RouteHandler](http://www.brainthud.com/cards/5218/24821/give-an-example-of-how-you-would-create-a-custom-route-處理器到重新路由,請求上帶有一個-一定的價值,在最接受-HTTP-他)。 –

回答

1

兩個選項我所知道的是:

使用URL Rewriter在全球範圍內採取的每一個和所有路由護理。優點是(我希望)你的發佈者確實有一些標準的URL,你可以轉換成友好的MVC路由。

如果沒有,那麼你可能必須編寫自己的RouteHandler。不知道你是否可以在全球範圍內使用它,但你必須註冊很多(並不那麼難)。

public class CustomRouteHandler : MvcRouteHandler 
{ 
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext) 
    { 
    var acceptValue = requestContext.HttpContext.Request.Headers["Accept"]; 

    if(/* do something with the accept value */) 
    { 
     // Set the new route value in the 
     // requestContext.RouteData.Values dictionary 
     // e.g. requestContext.RouteData.Values["action"] = "Customer"; 
    } 

    return base.GetHttpHandler(requestContext); 
    } 
} 

然後將其註冊:

RouteTable.Routes.MapRoute(
    name: "Custom", 
    url: "{controller}/{action}", 
    defaults: new { controller = "Home", action = "Index" } 
).RouteHandler = new CustomRouteHandler(); 
相關問題