asp.net-mvc – 从Api控制器内生成绝对的url to action

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 从Api控制器内生成绝对的url to action前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用asp.net mvc4和我在“controller1”这个动作:
  1. [HttpGet]
  2. public async Task<string> Action1()
  3. {
  4. try
  5. {
  6. HttpClient cl = new HttpClient();
  7. string uri = "controller2/action2";
  8. HttpResponseMessage response = await cl.GetAsync(uri);
  9. response.EnsureSuccessStatusCode();
  10. return response.ToString();
  11. }
  12. catch
  13. {
  14. return null;
  15. }
  16. }

当我将uri设置为“http:// localhost:1733 / controller2 / action2”时,动作正常,但是不要将uri设置为“controller2 / action2”或“/ controller2 / action2”或“〜/ controller2 / action2”.

如何在没有硬编码uri的情况下写这个动作?

谢谢.

解决方法

使用:
  1. string uri = Url.Action("Action2","Controller2",new {},Request.Url.Scheme);

更新:

由于您使用API​​控制器并需要为常规控制器生成Url,所以您必须使用:

  1. string uri = this.Url.Link("Default",new { controller = "Controller2",action = "Action2" });

其中Default是在注册路由集合中定义的路由的名称,或者如果您已经为此操作创建了特定路由,请使用其名称和新{}作为第二参数.

对于MVC版本4,请在〜/ App_Start / RoutesConfig.cs检查您注册的路由.对于MVC版本3,请在您的Global.asax中检查您的RegisterRoutes方法.

猜你在找的asp.Net相关文章