开发者

Building URL or link in REST ASP.NET MVC

I want to build a URL at runtime when a resource is render to either XML or JSON. I can do this easily when the view is HTML and is rendering only parts of the resource, but when I render a resource that contains a links to another resource I want to dynamically generate the correct URL according the host (site) and resource specific URI part.

开发者_StackOverflow社区
<components>
   <component id = "1234" name = "component A" version = "1.0">
       <link rel = "/component" uri="http://localhost:8080/component/1234" />
   </component>
<components>

How do I make sure the 'uri' value is correct?


Use the ControllerContext.HttpContext to get to the HttpContextBase holding information about the current request:

var context = ControllerContext.HttpContext;
var host = string.Format("{0}://{1}:{2}/", 
                          context.Request.Url.Scheme, 
                          context.Request.Url.Host, 
                          context.Request.Url.Port);

and combine host with a url generated using a UrlHelper (cf. the Url property of the Controller class).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜