2013-05-05 46 views
3

我正在同一個項目中運行WebApi和Mvc(因此它們在進程中)。 Mvc主要用於爲ajax數據請求提供資源(頁面和生成的下載)和web api。從Mvc Action中獲取WebApi UrlHelper的一個實例

爲了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 }); 
    } 
} 

有上還有一些其他的方法,但這是真正的核心事情,它工作正常。

現在我想優化一個特定的頁面。而在以前我有兩個請求

  1. 下載HTML
  2. 做一個Ajax查詢得到一些數據(和一些鏈接)

現在我認識到優化的目的,最好是剛做一個在這種情況下。

  1. 下載已嵌入JSON數據的html。

問題是由於Mvc正在生成html,所以我無法創建似乎可行的Api UrlHelper。

我試圖

var url = new UrlHelper(new HttpRequestMessage(verb, controller.Request.Url.AbsoluteUri)); 
if (!url.Request.Properties.ContainsKey(HttpPropertyKeys.HttpConfigurationKey)) //http://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幫手以某種方式路由配置。

回答

6

爲什麼要創建一個?在MVC Controller和ApiController類中都有一個UriHelper的實例公開爲屬性。

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

編輯:更新後的代碼。雖然url helper是不同的,你可以使用MVC url helper來解析web api url。

EDIT2:正確的方法,如果你想從一個MVC UrlHelper得到的WebAPI路由使用的是

string url = Url.HttpRouteUrl("DefaultApi", new {httproute = "", controller = "test"}); 
+1

因爲這並不攜帶的WebAPI配置。 'MvcController.UrlHelper'和'ApiController.UrlHelper'實際上是不同的類,而不僅僅是不同的類實例。 – 2013-05-05 15:48:48

+0

@GeorgeMauer儘管如此,你仍然可以從MVC控制器url助手獲取web api URL。我更新了代碼。 – 2013-05-05 16:03:40

+0

你的代碼不正確,你似乎可以從mvc url helper訪問web api url,你必須使用'Url.HttpRouteUrl'。在我的情況下,因爲我想保持在ApiLinkMaker中的鏈接構建代碼,我想我可以直接傳入一個委託而不是UrlHelper。 – 2013-05-05 16:18:31

相關問題