使用SPA和Web Api进行非Api路由

时间:2013-11-15 15:22:46

标签: asp.net-mvc angularjs

我对MVC和路由都比较新,所以对我来说很简单。我已经尝试了几天来解决这个问题所以我实际上可能试图解决错误的问题或者不知道正确的搜索条件,所以这里就是这样。

我正在使用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'
    
    

谢谢

1 个答案:

答案 0 :(得分: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;
    }
}