如何在MVC4中创建对象后获取绝对URL

时间:2012-08-01 13:22:02

标签: asp.net-mvc-routing asp.net-mvc-4

我正在尝试获取刚刚创建的对象的URL:

code = HttpStatusCode.Created;
String location = Url.Route("ApiRoute", new {@id = bp.Id, @controller = "ProfileController" });
Response.AppendHeader("Location", location);

这里的路线

routes.MapHttpRoute(
    name: "ApiRoute",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

但它似乎已经从MVC3变为MVC4。

有人可以对此有所了解吗?

由于

1 个答案:

答案 0 :(得分:1)

您可以使用接受protocol参数的Url.RouteUrl()方法。这将返回一个完全限定的URL。

// Formatted for readability
code = HttpStatusCode.Created;
String location = Url.Route(
  "ApiRoute", 
  new {@id = bp.Id, @controller = "ProfileController" }, 
  "http"
);
Response.AppendHeader("Location", location);