The ASP. NET Web API routing, in a nutshell, is the process of mapping client requests to the corresponding action. In the article "asp 03, routing templates, routing conventions, routing settings", the experience of setting up routes through templates, conventions, and HTTP methods has the advantage of unifying the routing template into the Webapiconfig class in the App_start folder. , convenient management, but the disadvantage is not flexible enough.
Rest sees everything as a resource, and sometimes a resource with sub-resources such as customer and orders are closely related, and we may want to enter such a request: Customers/1/orders, but it is difficult to implement this route just by convention. In fact, the ASP. NET Web API prepares us for the route feature, which can be directly hit on the action and is very flexible and intuitive to use.
Here's how to use the route feature in ASP. MVC4.
Allow Route feature
First, you need to set it in Webapiconfig.
Using System.Web.Http;
Namespace MyRoutingAttributes4
{
public static Class Webapiconfig
{
public static void Register (Httpconfiguration config)
{
Set attribute Routing
Config. Maphttpattributeroutes ();
Config. Routes.maphttproute (
Name: "Defaultapi",
Routetemplate: "Api/{controller}/{id}",
defaults:new {id = routeparameter.optional}
);
Uncomment the following line of code to enable query support for operations that have a IQueryable or iqueryable<t> return type.
To avoid handling unexpected queries or malicious queries, use the validation settings on Queryableattribute to validate incoming queries.
For more information, please visit http://go.microsoft.com/fwlink/?LinkId=279712.
Config. Enablequerysupport ();
To disable tracing in your application, comment out or delete the following line of code
For more information, see: Http://www.asp.net/web-api
Config. Enablesystemdiagnosticstracing ();
}
}
}
The Maphttpattributeroutes method above is only available in newer versions of the ASP. If your version is low, you can uninstall the old version from the NuGet Package Manager console and install the latest version.
Uninstall-package Microsoft.aspnet.webapi–force
Install-package Microsoft.aspnet.webapi
Next, in Global.asax, you need to comment out the way you originally registered Webapiconfig, and adopt the new way, as follows:
public class WebApiApplication:System.Web.HttpApplication
{
protected void Application_Start ()
{
Arearegistration.registerallareas ();
Webapiconfig.register (globalconfiguration.configuration);
Web API, starting feature routing
Globalconfiguration.configure (Webapiconfig.register);
Filterconfig.registerglobalfilters (globalfilters.filters);
Routeconfig.registerroutes (routetable.routes);
Bundleconfig.registerbundles (Bundletable.bundles);
}
}
Running the project at this time may report the following error:
This is because when you download the latest version of the ASP. NET Web API, the latest version of Icrosoft is loaded. AspNet.WebApi.HelpPage. The latest version of the Helppage can be uninstalled, and then download the relatively old version.
Uninstall-package Microsoft.aspnet.webapi.helppage–force
Install-package Microsoft.aspnet.webapi.helppage-pre
Using the route feature
Create a Cusomter class.
Namespace Myroutingattributes4.models
{
public class Customer
{
public int Id {get; set;}
public string Name {get; set;}
}
}
Create an Order class.
Namespace Myroutingattributes4.models
{
public class Order
{
public int Id {get; set;}
Public decimal Total {get; set;}
public int CustomerId {get; set;}
Public customer customer {get; set;}
}
}
Create a database class to get the order collection.
Using System.Collections.Generic;
Using System.Linq;
Using Myroutingattributes4.models;
Namespace MyRoutingAttributes4
{
public class Database
{
public static ienumerable<order> Getordersbycustomerid (int customerId)
{
Return GetOrders (). Where (o = = O.customerid = = CustomerId);
}
private static ienumerable<order> getorders ()
{
Customer CUS1 = new Customer () {Id = 1, Name = "Zhang San"};
Customer CUS2 = new Customer () {Id = 2, Name = "John Doe"};
list<order> orders = new list<order> ()
{
New Order () {Id = 1, total = 80M, CustomerId = 1, Customer = Cus1},
New Order () {Id = 2, total = 100M, CustomerId = 1, Customer = Cus1},
New Order () {Id = 3, total = 120M, CustomerId = 2, Customer = Cus2}
};
return orders;
}
}
Create an empty API controller and write the following:
Using System.Collections.Generic;
Using System.Web.Http;
Using Myroutingattributes4.models;
Namespace Myroutingattributes4.controllers
{
public class Orderscontroller:apicontroller
{
[Route ("Customers/{customerid}/orders")]
[HttpGet]
Public ienumerable<order> findordersbycustomer (int customerId)
{
Return Database.getordersbycustomerid (CUSTOMERID);
}
}
}
Enter the following in the browser:
If you are using ASP. MVC4 for development, you might report the following error when the program first runs:
A System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B] System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from "System.Web.WebPages.Razor, version=2.0.0.0, Culture=neutral, publickeytoken=31bf3856ad364e35" (In the context "Default" In the "c:/windows/microsoft.net/assembly/gac_msil/system.web.webpages.razor/v4.0_2.0.0.0__31bf3856ad364e35/ System.Web.WebPages.Razor.dll "location). Type B originates from "System.Web.WebPages.Razor, version=3.0.0.0, Culture=neutral, publickeytoken=31bf3856ad364e35" (In the context "Default" In the "C:/windows/microsoft.net/framework/v4.0.30319/temporary ASP. NET Files/vs/feb7ce97/a525d58a/asse
This is because the latest version of Razor is used when downloading the latest version of the ASP. The following configuration is required in Web. config under the root directory:
<runtime>
<assemblybinding xmlns= "Urn:schemas-microsoft-com:asm.v1" >
......
<dependentAssembly>
<assemblyidentity name= "System.Web.WebPages.Razor" publickeytoken= "31bf3856ad364e35"/>
<bindingredirect oldversion= "2.0.0.0" newversion= "3.0.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
using the Routeprefix feature
If you want to add a prefix to all the actions in an API controller, you can hit the Routeprefix feature on the API controller.
For example, we want to be in this format: http://localhost/api/customers/1/orders
This modifies the Orderscontroller.
Using System.Collections.Generic;
Using System.Web.Http;
Using Myroutingattributes4.models;
Namespace Myroutingattributes4.controllers
{
[Routeprefix ("API")]
public class Orderscontroller:apicontroller
{
[Route ("Customers/{customerid}/orders")]
[HttpGet]
Public ienumerable<order> findordersbycustomer (int customerId)
{
Return Database.getordersbycustomerid (CUSTOMERID);
}
}
}
You can also use ~ in the route attribute to override the action's prefix rule.
Using System.Collections.Generic;
Using System.Web.Http;
Using Myroutingattributes4.models;
Namespace Myroutingattributes4.controllers
{
[Routeprefix ("API")]
public class Orderscontroller:apicontroller
{
[Route ("~/myapi/customers/{customerid:int}/orders")]
[HttpGet]
Public ienumerable<order> findordersbycustomer (int customerId)
{
Return Database.getordersbycustomerid (CUSTOMERID);
}
}
}
Routeprefix attribute definitions can also be prefixed with parameter variables:
[Routeprefix ("Api/{customerid}")]
public class Orderscontroller:apicontroller
Routing constraints
Parameter variables in a route can be constrained by the "{parameter variable name: constraint}".
[Route ("Users/{id:int}"]
Public User Getuserbyid (int id) {...}
[Route ("Users/{name}"]
Public User Getuserbyname (string name) {...}
Above, if the fragment variable ID is of type int, it is routed to the first action, if not, to the second action.
The built-in constraints for ASP. NET Web API include:
{X:ALPHA} constraint-Case English letter
{X:bool}
{X:datetime}
{X:decimal}
{x:double}
{X:float}
{X:guid}
{X:int}
{x:length (6)}
{x:length (1,20)} constraint length range
{X:long}
{x:maxlength (10)}
{x:min (10)}
{X:range (10,50)}
{X:regex (regular expression)}
You can set multiple constraints for one parameter variable at the same time:
[Route ("Api/{id:int:min (1)}")]
Implement the Ihttprouteconstraint interface to customize constraint rules. Implement a constraint that cannot be 0.
public class Nonzeroconstraint:ihttprouteconstraint
{
Idictionary<string, object> values, httproutedirection routedirection)
{
Object value;
if (values. TryGetValue (parametername, out value) && value! = null)
{
Long Longvalue;
If (value is long)
{
Longvalue = (long) value;
return longvalue! = 0;
}
String valuestring = convert.tostring (value, CultureInfo.InvariantCulture);
CultureInfo.InvariantCulture, out Longvalue))
{
return longvalue! = 0;
}
}
return false;
}
}
Register a custom constraint in Webapiconfig in the App_start folder.
public static Class Webapiconfig
{
public static void Register (Httpconfiguration config)
{
var constraintresolver = new Defaultinlineconstraintresolver ();
CONSTRAINTRESOLVER.CONSTRAINTMAP.ADD ("Nonzero", typeof (Nonzeroconstraint));
Config. Maphttpattributeroutes (Constraintresolver);
}
}
Use a custom constraint.
[Route ("{Id:nonzero}")]
Optional parameters and their default values
If a route parameter variable is optional, you must also give the parameter a default value.
[Route ("Api/{id:int?}")]
Public ienumerable<t> Get (int id = 8) {}
After the constraint, indicate optional, and set the default value for the ID in the method parameter.
Setting a name for a route
public class Bookscontroller:apicontroller
{
[Route ("Api/books/{id}", Name= "Getbookbyid")]
{
Implementation not shown ...
}
[Route ("Api/books")]
Public Httpresponsemessage Post
{
Validate and add book to database (not shown)
var response = Request.createresponse (httpstatuscode.created);
Generate a link to the new book and set the "Location header" in the response.
String uri = Url.link ("Getbookbyid", new {id = book. BookId});
Response. headers.location = new Uri (URI);
return response;
}
}
Route priority order
Route precedence is determined by the custom and Routeorder properties of the route attribute settings.
The Convention is:
1. Static fragment variables
2. Fragment variables with constraints
3. Fragment variables without constraints
4. A constrained wildcard fragment variable
5. Wildcard Fragment variables without constraints
The default value of the Routeorder property is 0, and the lower the value of the property, the earlier the row.
[Routeprefix ("Orders")]
public class Orderscontroller:apicontroller
{
[Route ("{id:int}")]//constrained parameter
Public httpresponsemessage Get (int id) {...}
[Route ("Details")] Literal
Public Httpresponsemessage getdetails () {...}
[Route ("Pending", Routeorder = 1)]
Public Httpresponsemessage getpending () {...}
[Route ("{customerName}")] Unconstrained parameter
Public Httpresponsemessage Getbycustomer (string customerName) {...}
[Route ("{*date:datetime}")] Wildcard
Public Httpresponsemessage Get (DateTime date) {...}
}
Above, the order of precedence for routing is:
Orders/details static fragment variable, Routeorder property value is 0
ORDERS/{ID} fragment variable with constraint, Routeorder property value is 0
Orders/{customername} fragment variable with no constraint, Routeorder property value is 0
Orders/{*date} wildcard fragment variable with constraint, Routeorder property value is 0
Orders/pending Routeorder Property value is 1
ASP. NET Web API Practice Series 04, routing is set through features such as Route