简体   繁体   English

使用 FromUri 将复杂对象传递给 ASP.NET Web API

[英]Passing Complex Objects to ASP.NET Web API Using FromUri

I want to bind the URL parameters to my Point object using attribute routing and the [FromUri] attribute such that the following URL is possible:我想使用属性路由和[FromUri]属性将 URL 参数绑定到我的Point对象,以便可以使用以下 URL:

/foo-1,2 /foo-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
}

I have tried the following Route attributes but none of these work:我尝试了以下 Route 属性,但这些都不起作用:

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

Note that I can't use query string parameters because a badly built third party service does not accept ampersands in their URL's (Yes it's that bad).请注意,我不能使用查询字符串参数,因为构建不良的第三方服务不接受其 URL 中的&符号(是的,就是这么糟糕)。 So I'm trying to build all query string parameters into the URL itself.所以我试图将所有查询字符串参数构建到 URL 本身中。

The two Options I'm aware of is:我知道的两个选项是:

Use URL Rewriter to Globally take care of every and all routes.使用URL 重写器全局处理所有路由。 The advantage is that (I would hope) your publisher does have some type of standard url you can transform into a friendly MVC route.优点是(我希望)您的发布者确实有某种类型的标准 url,您可以将其转换为友好的 MVC 路由。

If not then you'll probably have to write your own RouteHandler.如果没有,那么您可能必须编写自己的 RouteHandler。 Not sure if you could use this globally, but you'd have to register it a lot (not that hard really).不确定你是否可以在全球范围内使用它,但你必须注册很多(真的没有那么难)。

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

Then register it:然后注册它:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM