【问题标题】:Passing Complex Objects to ASP.NET Web API Using FromUri使用 FromUri 将复杂对象传递给 ASP.NET Web API
【发布时间】:2016-03-08 16:52:32
【问题描述】:

我想使用属性路由和[FromUri] 属性将 URL 参数绑定到我的 Point 对象,以便可以使用以下 URL:

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

我尝试了以下 Route 属性,但这些都不起作用:

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

请注意,我不能使用查询字符串参数,因为构建不佳的第三方服务不接受其 URL 中的 & 符号(是的,这很糟糕)。所以我正在尝试将所有查询字符串参数构建到 URL 本身中。

【问题讨论】:

  • 您可能需要考虑使用 URL-Rewriter 在 URL 转换为 MVC 之前对其进行重写。会让任何 url 的事情变得非常容易。
  • @ErikPhilips 我正在考虑编写某种过滤器或模型绑定器来做同样的事情。我想回退到 IIS 是一个有效的选择。
  • 模型绑定器在选择路线的过程中很晚。你可能需要写一个RouteHandler。

标签: c# asp.net .net asp.net-web-api attributerouting


【解决方案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();

【讨论】:

    猜你喜欢
    • 2014-10-28
    • 2016-06-12
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    相关资源
    最近更新 更多