ASP. net web api required: feature routing, api required

Source: Internet
Author: User

ASP. net web api required: feature routing, api required

1. What is a special route?

Feature routing refers to marking RouteAttribute or custom feature classes that inherit from RouteAttribute on the Controller or ACTION and specifying the route Url string to implement route ing. add or Routes. mapHttpRoute is more flexible and intuitive.

To use the feature routing function, you must first enable ing to the feature routing in Application_Start. The Code is as follows:

GlobalConfiguration. Configuration. MapHttpAttributeRoutes (); // or add: config. MapHttpAttributeRoutes () in the WebApiConfig. Register Method ();

Ii. Usage of feature Routing

1. Basic route ing

        [Route("api/Values")]        public IEnumerable<string> Get()        {            return new string[] { "value1", "value2" };        }

Access address: http: // localhost: 34732/api/values. The result is as follows:

2. Route ing to parameters

        [Route("api/Values/{id}")]        public string Get2(int id)        {            return "value:" + id.ToString();        }

Access address: http: // localhost: 34732/api/values. The result is as follows:

3. Multi-feature Routing

        [Route("api/Values/{value1}/{value2}")]        [Route("api/Demo/{value2}/{value1}")]        public IEnumerable<string> Get3(string value1, string value2)        {            return new[] { value1, value2 };        }

Access address: http: // localhost: 34732/api/values/a/B or http: // localhost: 34732/api/demo/a/B. The result is as follows:

4. Default (default) parameter Routing

// Method 1 [Route ("api/Values/option/{key}/{value ?} ")] Public Dictionary <string, string> Get4 (string key, string value =" test ") {return new Dictionary <string, string> () {key, value }};}// method 2 [Route ("api/Values/option/{key}/{value = test}")] public Dictionary <string, string> Get5 (string key, string value) {return new Dictionary <string, string> () {key, value }};}

Access address: http: // localhost: 34732/api/Values/option/a, http: // localhost: 34732/api/Values/option/a/api result:

5. Parameter constraint Routing

        [Route("api/Values/constraint/{id:range(1,10)}")]        public string Get6(int id)        {            return "value:" + id.ToString();        }

Access address: http: // localhost: 34732/api/Values/constraint/10, http: // localhost: 34732/api/Values/constraint/11. The result is as follows:

The following table describes how to use the parameter constraints provided by the system (picture from Jiang Jinnan ):

6. wildcard (*) routing variable

        [Route("api/Values/many/{isOk:bool}/{*getDate:datetime}")]        public IHttpActionResult Get7(bool isOk, DateTime? getDate = null)        {            return Json(new { Ok = isOk, Date = getDate });        }

Access address: http: // localhost: 34732/api/Values/true/, Http: // localhost: 34732/api/Values/false/JuneThe result is as follows:

7. Route ing (binding) to complex parameters

[ModelBinder] // enables it to bind public class Point {public int x {get; set;} public int y {get; set ;}} by default ;}} // The first form [Route ("api/Values/model/{. x: int}/{. y: int}/{B. x: int}/{B. y: int} ")] public IEnumerable <Point> Get8 (Point a, Point B) {return new [] {a, B };} // Form 2 [Route ("api/Values/model")] public IEnumerable <Point> Get9 (Point a, Point B) {return new [] {, B };}

Access address: http: // localhost: 34732/api/Values/model/1/2/3/4, http: // localhost: 34732/api/Values/model? A. x = 10 & a. y = 20 & B. x = 30 & B. y = 40. The result is as follows:

8. Define the route prefix and cancel the route prefix.

[RoutePrefix ("api/demo")] // defines the Route prefix public class DemoController: ApiController {[Route ("Values")] // here you only need to define the parts except the route prefix. The complete route is: api/demo/Values public IEnumerable <string> Get () {return new string [] {"value1 ", "value2" };} [Route ("~ /Api/Values/{id} ")] // use ~ /Cancel the route prefix. Complete route: api/Values/{id} public string Get (int id) {return "value:" + id. ToString ();}

Access address: http: // localhost: 34732/api/demo/values, http: // localhost: 34732/api/values/1. The result is as follows:

 

As mentioned above, in addition to the constraints provided by the system, you can also customize the IHttpRouteConstraint constraint class. The following is an example of language constraints for switching between Chinese and English. The code implementation is as follows:

First, define a constraint class in both Chinese and English languages:

    public class CultureRouteConstraint : IHttpRouteConstraint    {        private static List<string> allowCultureList;        static CultureRouteConstraint()        {            allowCultureList = new List<string> { "zh-cn","en-us"}; //CultureInfo.GetCultures(CultureTypes.AllCultures).Select(c => c.Name).ToList();        }        public bool Match(System.Net.Http.HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values, HttpRouteDirection routeDirection)        {            if (values.ContainsKey(parameterName))            {                return allowCultureList.Any(c => c.Equals(values[parameterName].ToString(), StringComparison.OrdinalIgnoreCase));            }            return false;        }    }

Add it to the ultinlineconstraintresolver parameter and constraint ing dictionary. The Code is as follows:

            DefaultInlineConstraintResolver defaultInlineConstraintResolver = new DefaultInlineConstraintResolver();            defaultInlineConstraintResolver.ConstraintMap.Add("culture", typeof(CultureRouteConstraint));            // Web API routes            config.MapHttpAttributeRoutes(defaultInlineConstraintResolver);

Finally, you can use this constraint just like using a common constraint. before using the constraint, define two resource files: Default resource file (Chinese): Resources. resx, English resource file: Resources. en-us.resx

The two resource files are as follows:

The web api action is defined as follows:

[Route ("api/Values/constraint/{culture: culture}/{name}")] public string Get10 (string culture, string name) {CultureInfo currentCultureInfo = CultureInfo. currentCulture; CultureInfo currentCultureUIInfo = CultureInfo. currentUICulture; try {Thread. currentThread. currentCulture = Thread. currentThread. currentUICulture = new CultureInfo (culture); return Resources. resourceManager. getString (name. toString ();} finally // The Thread pool must be restored to the default status {Thread. currentThread. currentCulture = currentCultureInfo; Thread. currentThread. currentUICulture = currentCultureUIInfo ;}}

Access address: http: // localhost: 34732/api/Values/constraint/Zh-cn/Hello, http: // localhost: 34732/api/Values/constraint/En-usThe/hello result is as follows:

If you access other languages, such as http: // localhost: 34732/api/Values/constraint/Zh-tw/Hello, it will be unable to map to ACTION due to constraints, and thus the prompt cannot find the page, as shown below:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.