Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating url for a resource in asp.net web api outside of ApiController

Looking for a way to construct or generate a url for a specific resource in asp.net web api. It can be done in the controller since it inherits from ApiController hence you get the UrlHelper.

I am looking to construct resource url out of the context of the ApiController.

like image 430
Eatdoku Avatar asked May 07 '12 23:05

Eatdoku


1 Answers

Here is what I did:

  • Requires HttpContext/Request, so might not work in Application_Start.
  • Only tested in WebApi 1
  • Only works for routes registered in GlobalConfiguration (but if you have some other one, just pass it in instead)
// given HttpContext context, e.g. HttpContext.Current
var request = new HttpRequestMessage(HttpMethod.Get, context.Request.Url) {
    Properties = {
        { HttpPropertyKeys.HttpConfigurationKey, GlobalConfiguration.Configuration },
        { HttpPropertyKeys.HttpRouteDataKey, new HttpRouteData(new HttpRoute()) },
        { "MS_HttpContext", new HttpContextWrapper(context) }
    }
};

var urlHelper = new UrlHelper(request);
like image 156
Andrey Shchekin Avatar answered Nov 16 '22 00:11

Andrey Shchekin