【问题标题】:Get route by name按名称获取路线
【发布时间】:2015-02-15 16:47:21
【问题描述】:

我正在开发一个带有超媒体的 asp.net web api。现在我正在创建一个链接创建器,它创建一个指向控制器公开的资源的链接。它应该支持属性路由,我已经通过反射解决了,而且还支持在 Owin.AppBuilder 中指定的映射路由:

public void Configuration(IAppBuilder appBuilder)
{
    var config = new HttpConfiguration();
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "{controller}/{id}",
        defaults: new { controller = "Home", id = RouteParameter.Optional }
        );
    // ...
}

我可以为此使用UrlHelper 类,但这取决于当前请求,并且我创建的链接可能指向另一个控制器,因此与当前请求没有关系。所以我需要为名为@9​​87654323@ 的路由加载路由配置数据。有什么办法吗?

【问题讨论】:

    标签: c# asp.net-web-api asp.net-mvc-routing hypermedia


    【解决方案1】:

    如果你可以使用 Route 属性,你可以通过 name 属性命名你的路由,我所做的是我在 RoutesHelper 中定义了我的路由,当我定义我的控制器路由时,我引用了这个常量,当我想使用 CreatedAtRoute例如我引用相同的 routeName 并传递参数来构造路由。

    假设我的控制器叫做 PeopleController,那么我会将我的控制器定义为:

    [Route("api/people/{id:int:min(1)?}", Name = RoutesHelper.RouteNames.People)]
    public class PeopleController : ApiController
    {
       // controller code here
    }
    

    哪里的RoutesHelper是这样的:

    public static class RoutesHelper
    {
        public struct RouteNames
        {
            public const string People = "People";
            // etc...
        }
    }
    

    例如,现在在我的 Post 方法中,我像这样使用 CreateAtRoute:

    [HttpPost]
    [ResponseType(typeof(PersonDto))]
    public async Task<IHttpActionResult> AddAsync([FromBody] personDto dto)
    {
        // some code to map my dto to the entity using automapper, and save the new entity goes here
        //.
        //.
    
        // here, I am mapping the saved entity to dto 
        var added = Mapper.Map<PersonDto>(person);
    
        // this is where I reference the route by it's name and construct the route parameters.
        var response = CreatedAtRoute(RoutesHelper.RouteNames.People, new { id = added.Id }, added);
    
        return response;
    }
    

    希望这会有所帮助。

    【讨论】:

    • 谢谢,但恐怕这并不能完全解决问题,因为我正在制作一个用于创建链接的组件,该组件必须支持属性路由和在 owin 容器中配置的路由,而问题在于从容器中读取路由模板。
    猜你喜欢
    • 1970-01-01
    • 2016-03-26
    • 2015-02-12
    • 2013-02-28
    • 2015-09-14
    • 2014-03-05
    • 2011-04-26
    • 1970-01-01
    相关资源
    最近更新 更多