Home  >  Article  >  Backend Development  >  Detailed explanation of ASP.NET attribute routing examples of WEB API

Detailed explanation of ASP.NET attribute routing examples of WEB API

Y2J
Y2JOriginal
2017-04-25 15:49:222226browse

The following is conventional MVC routing

 config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
      );

If we want to achieve routing with effects similar to the following, it is more troublesome to use conventional convention routing.

order/Miles/三只松鼠干果/2袋
order/2017/1/13

It would be simpler if you use attribute routing.

If you create a new WEB API project, open the WebApiConfig.cs file in the App_Start directory and add the following code to enable attribute routing configuration.

 config.MapHttpAttributeRoutes();

Attribute routing can also be mixed with convention routing, as follows:

 public static void Register(HttpConfiguration config)
    {
      // Web API 配置和服务

      // Web API 路由
      config.MapHttpAttributeRoutes();

      config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
        constraints: new { id=@"\d+"}
      );
    }

Mark the attribute on the method to use attribute routing, as follows:

 [Route("order/{UserNickName}/{ProductName}/{count}")]

Test results ( The URL is encoded, otherwise a 400 error will be reported)


##Normally, all routes in the same controller start with the same prefix##. #
  [Route("api/books")]
  [Route("api/books/{id:int}")]
  [Route("api/books")]

This is obviously more troublesome. So we use the [RoutePrefix] attribute to set a public prefix

Test result

If [RoutePrefix is ​​used ], for some special APIs, we can use wavy lines to rewrite the routing prefix, as follows:

Test results (under the same class)

The route prefix can also contain parameters, as follows

Test results

##You can add parameter constraints in the route, as follows

Test result

If the parameter is not Int type, the route will not be matched

The following are some constraints that will be supported

You can use multiple constraints, but Use colons to separate

[Route("users/{id:int:length(1,3)}")]
public User GetUserById(int id) { ... }

The result

If it is not within the range, it will not match

Custom routing constraints need to implement the IHttpRouteConstraint interface. For details, check the official

public class NonZeroConstraint : IHttpRouteConstraint
{
  public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, 
    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);
      if (Int64.TryParse(valueString, NumberStyles.Integer, 
        CultureInfo.InvariantCulture, out longValue))
      {
        return longValue != 0;
      }
    }
    return false;
  }
}

Registration constraints

public static class WebApiConfig
{
  public static void Register(HttpConfiguration config)
  {
    var constraintResolver = new DefaultInlineConstraintResolver();
    constraintResolver.ConstraintMap.Add("nonzero", typeof(NonZeroConstraint));

    config.MapHttpAttributeRoutes(constraintResolver);
  }
}

Use constraints

[Route("{id:nonzero}")]
public HttpResponseMessage GetNonZero(int id) { ... }

Optional URI parameters and default values

You can make a route parameter an optional URI parameter by adding a question mark to mark it. If a route parameter is optional, you must define a default value for the method parameter.

public class BooksController : ApiController
{
  [Route("api/books/locale/{lcid:int?}")]
  public IEnumerable<Book> GetBooksByLocale(int lcid = 1033) { ... }
}

Or define the default value in the routing template

public class BooksController : ApiController
{
  [Route("api/books/locale/{lcid=1033}")]
  public IEnumerable<Book> GetBooksByLocale(int lcid) { ... }
}

The above is the detailed content of Detailed explanation of ASP.NET attribute routing examples of WEB API. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn