加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net – 从Mvc Action中获取WebApi UrlHelper的实例

发布时间:2020-12-16 09:24:44 所属栏目:asp.Net 来源:网络整理
导读:我在同一个项目中运行WebApi和Mvc(所以它们在进程中). Mvc主要用于服务资产(页面和生成的下载)以及用于ajax数据请求的web api. 为了成为RESTish,大多数WebApi请求都包含一组由以下类生成的链接: public class ApiLinkMaker{ public ApiLinkMaker(UrlHelper
我在同一个项目中运行WebApi和Mvc(所以它们在进程中). Mvc主要用于服务资产(页面和生成的下载)以及用于ajax数据请求的web api.

为了成为RESTish,大多数WebApi请求都包含一组由以下类生成的链接:

public class ApiLinkMaker
{
    public ApiLinkMaker(UrlHelper url,string authority) {
        this.url = url;
        this.authority = authority;
    }
    public ApiLinkMaker(ApiController controller)
        : this(controller.Url,controller.Request.RequestUri.Authority) { }

    public string MakeLink(string controller,string id) {
        return "//" + authority + url.Route("DefaultApi",new { controller = controller,id = id });
    }
}

那里还有其他一些方法,但这确实是事情的核心,它运作良好.

现在我想优化特定页面.以前我有两个请求

>下载html
>执行Ajax查询以获取一些数据(和一些链接)

现在我意识到,出于优化目的,在这种情况下最好只做一个.

>下载嵌入了JSON的数据的html.

问题是,由于html是由Mvc生成的,我无法创建一个似乎有用的Api UrlHelper.

我试过了

var url = new UrlHelper(new HttpRequestMessage(verb,controller.Request.Url.AbsoluteUri));
if (!url.Request.Properties.ContainsKey(HttpPropertyKeys.HttpConfigurationKey)) //https://stackoverflow.com/questions/11053598/how-to-mock-the-createresponset-extension-method-on-httprequestmessage
   url.Request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey,new HttpConfiguration());

但这仍然会爆炸

System.ArgumentException was unhandled by user code
  HResult=-2147024809
  Message=A route named 'DefaultApi' could not be found in the route collection.
Parameter name: name
  Source=System.Web.Http
  ParamName=name
  StackTrace:
       at System.Web.Http.HttpRouteCollection.GetVirtualPath(HttpRequestMessage request,String name,IDictionary`2 values)
       at System.Web.Http.Routing.UrlHelper.GetHttpRouteHelper(HttpRequestMessage request,String routeName,IDictionary`2 routeValues)
       at System.Web.Http.Routing.UrlHelper.GetHttpRouteHelper(HttpRequestMessage request,Object routeValues)
       at System.Web.Http.Routing.UrlHelper.Route(String routeName,Object routeValues)
       at MyProject.Models.ApiLinkMaker.MakeLink(String controller,String id) in w:MyProjectModelsApiLinkMaker.cs:line 42
       ...

这让我觉得我错了 – 我需要以某种方式从api路由配置创建url帮助器.

解决方法

为什么创建一个?在MVC Controller和ApiController类上都有一个UriHelper实例作为属性公开.

public ActionResult Index()
    {
        string url = Url.RouteUrl("DefaultApi",new {httproute = "",controller = "test"});
        return View();
    }

编辑:更新的代码.虽然url助手不同,但您可以使用MVC url助手来解析Web api url.

Edit2:如果你想从Mvc UrlHelper获取webapi路由,使用正确的方法是

string url = Url.HttpRouteUrl("DefaultApi",controller = "test"});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读