Asp.net mvc 从Api控制器中生成操作的绝对url
我正在使用asp.net mvc4,我在“controller1”中执行以下操作:Asp.net mvc 从Api控制器中生成操作的绝对url,asp.net-mvc,Asp.net Mvc,我正在使用asp.net mvc4,我在“controller1”中执行以下操作: [HttpGet] public async Task<string> Action1() { try { HttpClient cl = new HttpClient(); string uri = "controller2/action2"; HttpResponseMe
[HttpGet]
public async Task<string> Action1()
{
try
{
HttpClient cl = new HttpClient();
string uri = "controller2/action2";
HttpResponseMessage response = await cl.GetAsync(uri);
response.EnsureSuccessStatusCode();
return response.ToString();
}
catch
{
return null;
}
}
[HttpGet]
公共异步任务Action1()
{
尝试
{
HttpClient cl=新的HttpClient();
字符串uri=“controller2/action2”;
httpresponsemessageresponse=await cl.GetAsync(uri);
response.EnsureSuccessStatusCode();
返回response.ToString();
}
抓住
{
返回null;
}
}
当我将uri设置为时http://localhost:1733/controller2/action2“
该操作可以正常工作,但在uri设置为“controller2/action2”或“/controller2/action2”或“~/controller2/action2”的情况下,该操作永远不会工作
如何在不硬编码uri的情况下编写此操作
谢谢。使用:
string uri = Url.Action("Action2", "Controller2", new {}, Request.Url.Scheme);
更新:
由于您使用的是API控制器,并且需要生成常规控制器的Url,因此必须使用:
string uri = this.Url.Link("Default", new { controller = "Controller2", action = "Action2" });
其中,Default
是注册的routes集合中定义的route
的名称,或者如果您已经为此操作创建了特定的路由,请使用它的名称和new{}
作为第二个参数
对于MVC版本4,请在
~/App\u Start/routeConfig.cs
上检查注册的路由。对于MVC版本3,请检查全局中的RegisterRoutes
方法。asax
另一个可能更简单的答案是在WebApi类中创建UrlHelper的实例:
var url = new UrlHelper(System.Web.HttpContext.Current.Request.RequestContext);
item.Url = url.Action("Doc", "Editor", new {id=1});
传入当前请求上下文,您就是黄金。“System.Web.Http.Routing.UrlHelper”不包含“Action”的定义,并且找不到接受“System.Web.Http.Routing.UrlHelper”类型的第一个参数的扩展方法“Action”(您是否缺少using指令或程序集引用?)我缺少一些参考?您要生成绝对Url的操作,是WebApi方法还是常规控制器操作?不是常规控制器内的操作。正如我刚才所说的那样,
”http://localhost:1733/controller2/action2“
操作有效,我只是不想硬编码我的操作重要的一点是Url.Link
<代码>Url。路由生成相对Url。