Objective
In this section, we talk about routing in ASP. Before we talk about routing, we first look at the model bindings in ASP. One of the problems I met in the project is that I came up with this question first.
Review ASP. NET core model bindings
We have a scenario where we modify individual attributes in the profile, and the value of each property is definitely different, so we define the value as object, as in the following model.
Public class Blogviewmodel { publicstringgetset;} Public Object Get Set ; } }
We submit them at the front desk, as follows:
<Scripttype= "Text/javascript"> $(function () { varModel={prop:"Jeffcky", Value:"Cnblogs" }; $("#btn"). On ("Click", function() {$.ajax ({URL:"/home/index", type:"Post", ContentType:"Application/x-www-form-urlencoded;charset=utf-8", DataType:"JSON", Data:model, success:function(data) {}}); }); });</Script>
We receive the passed object in the background.
[HttpPost] Public Iactionresult Index (Blogviewmodel model) { return View ();
At this point we see that defining a value type As object does not receive a value at all, and it certainly works when I modify it to a string. I thought it would be good to receive any object from the form before, but in practice it was not as we would expect it to be (a solution was not found for the moment). In this case I had to use contenttype: "Application/json" to solve, as follows:
$ (function () { var model = {prop: "Jeffcky", Value: "Cnblogs"}; $ ("#btn"). On ("click", Function () { $.ajax ({ URL: "/home/index", type: "Post", ContentType : "Application/json;charset=utf-8", dataType: "JSON", json.stringify(model), Success:function (data) {}});}) ;
[HttpPost] Public Iactionresult Index ([frombody] Blogviewmodel model) { return View (); }
You can only change your mind to solve it, okay, here we come to the end of the problem with the object leveraging model bindings, and then we begin to tell about the route.
ASP. NET Core Mvc/webapi routing action
Whether it's in ASP. MVC/WEBAPI or ASP. NET Core Mvc/webapi, we've been talking about routing, why do we have to say it every time, because it's important that data interactions from the foreground to the back end need to be routed through routing, so we need the ASP. Core focus come on, we need to talk about what the benefits of routing are, please look down.
(1) SEO
SEO is Search engine optimization, we translate is the search engine optimization, the introduction of routing is to show a friendly seo, a friendly SEO that can very accurately describe the need to request resources, for users it can better go to get the content, Can increase the number of Web site visits, of course, it can also be easily indexed to search engines.
(2) URL does not need to be mapped to a file
If there is no route, if there is a request that needs to be mapped to a real physical file on disk, there is a request that we have full control over, and when a certain HTTP request comes in, we can boot to the corresponding action method on a controller.
(3) Long URLs and extensions will be eliminated
We were able to know that when we visited a page that was directly rendered with an. aspx or HTML extension, we now have a route that does not require an extension at all and shortens the length of the URL.
Okay, let's finish with the benefits of routing, and we'll look at what the route is in ASP.
ASP. NET Core Mvc/webapi routing method create default route
This is not much to say, when we create an ASP. NET core application, the default route is created in startup as follows:
public class startup{public void Configureservices (iservicecollection services) { services. Addmvc (); } public void Configure (Iapplicationbuilder app, Ihostingenvironment env, iloggerfactory loggerfactory) { App. USEMVC (routes = { routes. MapRoute ( name: "Default", Template: "{controller=home}/{action=index}/{id}");} );} }
This is the default for us to create, looking a bit uncomfortable, I still used to modify it as follows the same routing configuration.
App. USEMVC (routes = { routes. MapRoute ( name: "Default", Template: "{controller}/{action}/{id}", defaults:new {controller = "Home ", action =" Index "});
Extending the default route
The above is just the default route we created when we need additional custom extensions for specific requirements, so we'll extend a route like above.
App. USEMVC (routes = {
//Extended route Routes. MapRoute ( name: "About-route", Template: "About", defaults:new {controller = "Home", action = "About"});
routes. MapRoute ( name: "Default", Template: "{controller}/{action}/{id}", defaults:new {controller = "Home" , action = "Index"});
Using Routing Attributes
We can also configure the routing characteristics for the controller and the action method, as follows:
[Route ("[Controller]")] public class Homecontroller:controller { private iblogrepository _blogrepository; Public HomeController (iblogrepository blogrepository) { _blogrepository = blogrepository; } [Route ("[Action]")] Public Iactionresult Index () { return View (); } [Route ("Index")] [HttpPost] Public Iactionresult Index ([frombody] Blogviewmodel model) { return View (); } }
The above [Route ([Controller])] and [Route ("[Action]]]) are all references to the controller name and method name of the declaration, namely the Home controller and the index method, so the two action methods above are matched/home/ Index is just a different way to request. In the official website has the way that uses the route middleware, has the need to refer to: "Https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing"
RESTful style Routing
For restful style routing we are more used on the request of the ASP. NET Core Webapi interface, as follows:
[Route ("Api/[controller]")] public class Blog:controller { [httpget] api/blogpublic IEnumerable< string > Get () { return new string[] {"Hello", "world!"}; } [HttpPost ("Post")] api/blog/postpublic iactionresult postblog ([frombody] Blogviewmodel model) { return View (); } }
So the question is, if there are parameters we should carry out how to pass it, of course there are solutions, as follows:
[HttpPost ("{ID}")] public void postupdate (int id, [frombody] string value) { }
At this point the front desk requests are as follows:
$ ("#btn"). On ("click", Function () { $.ajax ({ URL: "/API/BLOG/2", type: "Post", ContentType: " Application/json;charset=utf-8 ", dataType:" JSON ", data:JSON.stringify (" Jeffcky "), success:function (data) { } }); });
Working with constraints
For the argument type to be illegal, we can achieve our goal by constraining the parameters as follows:
[HttpPost ("{id:int}")] public void postupdate (int id, [frombody] string value) { }
or the parameter constraint is a GUID, as follows:
[HttpPost ("{id:guid}")] public void Postupdate (string ID, [Frombody] string value) { }
Of course, there are other types of parameter constraints are not listed.
Summarize
In this section we explain the use of routes in ASP. NET core, more basic things, more in-depth things to see the official website information, if there is less understanding and doubts about the place, please indicate in the comments that see will immediately reply.
How does ASP. NET Core Mvc/webapi build a route?