官术网_书友最值得收藏!

Routing in SPAs

In SPAs, the complexity needed from ASP.NET Core MVC routing is low, because routing will mostly be taken care of by the frontend code. On the ASP.NET Core MVC end, we will use routing to support client-side routing capabilities.

For this, we will take advantage of conventional routing and set up two catch-all routes, as follows:

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");

routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new { controller = "Home", action = "Index" });
});

The first default route was discussed earlier in this section. This will enable all incoming requests to be directed to the Index method of the HomeController.

The second route uses the MapSpaFallbackRoute method, instead of the common MapRoute method. The difference between these methods is a small but important one: the MapSpaFallbackRoute method registers a route just like MapRoute does, but whenever a route matches its template and has a file extension at the end, the URL will be treated as a static file request and will return the file as is, without executing an action method. For example, a call to http://example.com/users will execute the Index method within the UsersController class. A call to http://example.com/images/user.png will return a file named user.png from a folder named images.

This capability is extremely important for SPAs that request many static files from the server, such as images, videos, HTML pages, JavaScript files, CSS files, and more.

These two routes enable everything that is needed for the frontend of the SPA to operate correctly. The first route enables using different MVC controllers, which is sometimes needed in large SPAs, and the second route enables the use of routing on the client-side and the serving of static files when requested.

主站蜘蛛池模板: 洪湖市| 策勒县| 广河县| 宜阳县| 浑源县| 汉沽区| 策勒县| 临桂县| 庐江县| 灵寿县| 青川县| 丹东市| 古丈县| 嘉荫县| 贵南县| 菏泽市| 吉水县| 平罗县| 新乡县| 横山县| 黎城县| 乐平市| 凤山县| 山阳县| 邯郸市| 包头市| 彭泽县| 忻州市| 集贤县| 溧阳市| 于都县| 永川市| 特克斯县| 阿克苏市| 长武县| 信宜市| 内乡县| 杨浦区| 新营市| 浪卡子县| 榆林市|