MVC Routes within WebAPI controller

百般思念 提交于 2019-12-03 15:59:39

The routing tables for MVC and Web API are completely different. While the syntax looks similar, the route table they operate on is different.

However, MVC uses static objects for configuration, so you can access the global MVC route table from within an API controller using System.Web.Routing.RouteTable.Routes.

This won't allow you to use Url.Link however, so I would suggest using a constant within your route registration for the format.

Here is a much more cleaner way to generate links to MVC routes from WebApi. I use this method in a custom base api controller.

protected string MvcRoute(string routeName, object routeValues = null)
{
    return new System.Web.Mvc.UrlHelper(System.Web.HttpContext.Current.Request.RequestContext)
       .RouteUrl(routeName, routeValues, System.Web.HttpContext.Current.Request.Url.Scheme);

}

Using Richards hint of where to find the routes, I have put together the following function:

    // Map an MVC route within ApiController
    private static string _MvcRouteURL(string routeName, object routeValues)
    {
        string mvcRouteUrl = "";

        // Create an HttpContextBase for the current context, used within the routing context
        HttpContextBase httpContext = new System.Web.HttpContextWrapper(HttpContext.Current);

        // Get the route data for the current request
        RouteData routeData = HttpContext.Current.Request.RequestContext.RouteData;

        // Create a new RequestContext object using the route data and context created above
        var reqContext = new System.Web.Routing.RequestContext(httpContext, routeData);

        // Create an Mvc UrlHelper using the new request context and the routes within the routing table
        var helper = new System.Web.Mvc.UrlHelper(reqContext, System.Web.Routing.RouteTable.Routes);

        // Can now use the helper to generate Url for the named route!
        mvcRouteUrl = helper.Action(routeName, null, routeValues, HttpContext.Current.Request.Url.Scheme);

        return mvcRouteUrl;
    }

It's a bit raw but did the job for me, just thought I'd put this here in case anyone else had the same problem!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!