ASP.NET Web API - Cấu hình Web API
Cấu hình Web API
Web API hỗ trợ cấu hình dựa trên mã. Không thể cấu hình trong tệp web.config. Chúng ta có thể cấu hình Web API để tùy chỉnh hành vi của cơ sở hạ tầng lưu trữ Web API và các thành phần như tuyến đường, trình định dạng, bộ lọc, DependencyResolver, MessageHandlers, ParamterBindingRules, thuộc tính, dịch vụ, v.v.
Chúng tôi đã tạo một dự án Web API đơn giản trong phần Tạo dự án Web API. Dự án Web API bao gồm lớp WebApiConfig mặc định trong thư mục App_Start và cũng bao gồm Global.asax như được hiển thị bên dưới.
Global.asax
public class WebAPIApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
//other configuration
}
}
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// configure additional webapi settings here..
}
}
Quá trình cấu hình Web API bắt đầu khi ứng dụng khởi động. Nó gọi GlobalConfiguration.Configure(WebApiConfig.Register) trong phương thức Application_Start. Phương thức Configure() yêu cầu phương thức gọi lại nơi Web API đã được cấu hình trong mã. Theo mặc định, đây là phương thức tĩnh WebApiConfig.Register().
Như bạn có thể thấy ở trên, phương thức WebApiConfig.Register() bao gồm một tham số có kiểu HttpConfiguration sau đó được sử dụng để cấu hình Web API. HttpConfiguration là lớp chính bao gồm các thuộc tính sau mà bạn có thể ghi đè hành vi mặc định của Web API.
Thuộc tính | Mô tả |
---|---|
DependencyResolver | Gets or sets the dependency resolver for dependency injection. |
Filters | Gets or sets the filters. |
Formatters | Gets or sets the media-type formatters. |
IncludeErrorDetailPolicy | Gets or sets a value indicating whether error details should be included in error messages. |
MessageHandlers | Gets or sets the message handlers. |
ParameterBindingRules | Gets the collection of rules for how parameters should be bound. |
Properties | Gets the properties associated with this Web API instance. |
Routes | Gets the collection of routes configured for the Web API. |
Services | Gets the Web API services. |
Truy cập MSDN để tìm hiểu về tất cả các thành viên của HttpConfiguration