我在同一个项目中运行WebApi和Mvc(所以它们在进程中). Mvc主要用于服务资产(页面和生成的下载)以及用于ajax数据请求的web api. 为了成为RESTish,大多数WebApi请求都包含一组由以下类生成的链
为了成为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, String routeName, Object routeValues) at System.Web.Http.Routing.UrlHelper.Route(String routeName, Object routeValues) at MyProject.Models.ApiLinkMaker.MakeLink(String controller, String id) in w:\MyProject\Models\ApiLinkMaker.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", new {httproute = "", controller = "test"});