AngularJS with MVC 6

坚强是说给别人听的谎言 提交于 2019-12-02 07:58:58

问题


This is an MVC 6/WebApi application. I'm attempting to use WebApi on the backend with AngularJS on the frontend.

I have two static files: index.html and login.html
(There will eventually be more static files.)

My Angular app is contained in the index.html while views (such as /login) are loaded from static files (i.e. login.html).

If I go to my root URL, index.html is loaded just fine. However, if I go to /login, I receive a 404 page not found.

Now, let it be said, I DO NOT want to bog down my application with a bunch of controllers and views as it's unnecessary to simply serve static files. That's overkill.

I have my routes setup to serve API calls (i.e. ~/api/whatever). How I get MVC 6 to ignore all other routes?

FYI, it also appears that MapPageRoute is deprecated in MVC 6?

EDIT:
One thing I've done to actually get it working is add my own middleware to intercept the request. The code below is added after all of my default middleware in the Configure method:

app.Use(next => async context =>
{
    if (context.Request.Path.Value.StartsWith("/api"))
        await next.Invoke(context);
    else
        await context.Response.WriteAsync(System.IO.File.ReadAllText("index.html"));
});

This seems a bit much and it's just a hack. All it does is allows any request that begins with "/api" to go through (which is then picked up by the MVC middleware), but any other call is served with the contents of the index.html. So, if my requested URL is "/login", the index.html file is served, then Angular looks at the route and loads the login.html file into view.

Any other suggestions?


回答1:


Okay, so since something didn't exist in the MVC 6/ASP.NET 5 framework, I've created my own middleware that provides a lot more flexibility. It has been added to GitHub and is available through NuGet.

The project page is: https://github.com/a11smiles/AngularMiddleware




回答2:


I was able do what you are asking here. Basically, I added a catch all route to my index action:

[Route("{*path}")]

meaning if no MVC action does not exist, call my Index action and angular routing will take from there



来源:https://stackoverflow.com/questions/34051586/angularjs-with-mvc-6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!