2013-11-15 146 views
1

我對MVC和路由都很陌生。我一直在努力解決這個問題,所以我可能實際上試圖解決錯誤的問題或不知道正確的術語來搜索。使用SPA和Web Api的非Api路由

我正在用AngularJS和Web Api(4.5)創建SPA。我所有的觀點都是客戶端。所以服務器不知道可能存在於URI中的所有可能的路由。在用戶使用其中一個瀏覽器控件(回退,轉發,刷新,歷史記錄)並且服務器嘗試路由請求的URI之前,這不是問題。

我對處理這個問題的想法主要集中在將所有非API路由映射到應用程序的根目錄。

所以我想要知道MapHttpRoute的正確語法來選擇任何不試圖引用控制器(API)的路由或者是否有更好的方法來處理這個問題。

public static void Register(HttpConfiguration config) 
{ 
    config.MapHttpAttributeRoutes();    

    config.Routes.MapHttpRoute(
     name: "DefaultApi", 
     routeTemplate: "api/{controller}/{id}", 
     defaults: new { id = RouteParameter.Optional } 
    ); 
    // 
    // This doesn't work 
    // 
    config.Routes.MapHttpRoute(
     name: "Default", 
     routeTemplate: "{*catchall}" 
    ); 
} 
 
    This XML file does not appear to have any style information associated with it. The document tree is shown below. 
    
    
    No HTTP resource was found that matches the request URI 'http://localhost:9234/login'. 
    
    
    No route providing a controller name was found to match request URI 'http://localhost:9234/login' 
    
    

謝謝

回答

0

不是一個好主意,只是解決辦法

config.Routes.MapHttpRoute(
      name: "Default", 
      routeTemplate: "{*catchall}", 
      defaults: new { controller = "Spa"} 
      ); 

[AllowAnonymous] 
public sealed class SpaController : ApiController 
{ 
    public HttpResponseMessage Get() 
    { 
     var indexHtml = HostingEnvironment.MapPath("~/index.html"); 

     var stringContent = new StreamContent(File.OpenRead(indexHtml)); 
     var response = new HttpResponseMessage(HttpStatusCode.OK) {Content = stringContent}; 

     return response; 
    } 
}