Configuration Settings

WebAPI中的configuration settings定义在HttpConfiguration中。有一下成员:

  • DependencyResolver
  • Filters
  • Formatters
  • IncludeErrorDetailPolicy
  • Initializer
  • MessageHandlers
  • ParameterBindingRules
  • Properties
  • Routes
  • Services

在ASP.NET Hosting中配置WebApi

namespace WebApplication1
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// TODO: Add any additional configuration code. // Web API routes
config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}

OWIN Self-Hosting中配置WebAPI

使用OWIN进行self-Hosting,需要创建一个HttpConfiguration实例,在这个实例中添加一些配置,然后将这个实例传给Owin.UseWebApi的扩展方法。

public class Startup

{

public void Configuration(IAppBuilder appBuilder)

{

HttpConfiguration config = new HttpConfiguration();

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

Global Web API Services

HttpConfiguration.Services包含一些列的global services,WebAPI使用这些services执行各种各样的tasks,例如controller的选择以及content negotiation。

Services集合会被默认定义的services初始化,但是可以进行定义实现,一些services支持多个实例,一些仅支持一个实例。

支持单个实例的services

IActionValueBinder、IApiExplorer、IAssembliesResolver、IBodyModelValidator、IContentNegotiator、IDocumentationProvider、IHostBufferPolicySelector、IHttpActionInvoker、IHttpActionSelector、IHttpControllerActivator、IHttpControllerSelector、IHttpControllerTypeResolver、ITraceManager、ITraceWriter、IModelValidatorCache

支持多实例的services

IFilterProvider、ModelBinderProvider、ModelMetadataProvider、ModelValidatorProvider、ValueProviderFactory

将自定义的实现添加到支持多实例的service,可以使用Add和Insert的方式

config.Services.Add(typeof(IFilterProvider), new MyFilterProvider());
config.Services.Insert(typeof(IFilterProvider),0,new MyFilterProvider());

使用自定义的实现替换仅支持单实例的service

config.Services.Replace(typeof(ITraceWriter), new MyTraceWriter());

Per-Controller Configuration

使用per-controller方式可以重写如下设置:

  • Media-type formatters

  • Parameter binding rules

  • Services

    通过自定义实现IControllerConfiguration接口的特性,然后应用到controller上可以实现上述目标

    using System;

    using System.Web.Http;

    using System.Web.Http.Controllers;

    namespace WebApplication1.Controllers

    {

      public class UseMyFormatterAttribute : Attribute, IControllerConfiguration
    {
    public void Initialize(HttpControllerSettings settings,
    HttpControllerDescriptor descriptor)
    {
    // Clear the formatters list.
    settings.Formatters.Clear(); // Add a custom media-type formatter.
    settings.Formatters.Add(new MyFormatter());
    }
    } [UseMyFormatter]
    public class ValuesController : ApiController
    {
    // Controller methods not shown...
    }

    }

IControllerConfiguration接口的作用:如果某个控制器是使用此接口的特性修饰的,则将调用此接口来初始化该控制器设置。

IControllerConfiguration.Initialize方法包含两个参数:

  • HttpControllerSettings 这个对象是Configuration的一个子集,包含可以在per-controller时被重写的的对象
  • HttpControllerDescriptor 包含controller的描述信息

WebApi2官网学习记录---Configuring的更多相关文章

  1. WebApi2官网学习记录---Cookie

    Cookie的几个参数: Domain.Path.Expires.Max-Age 如果Expires与Max-Age都存在,Max-Age优先级高,如果都没有设置cookie会在会话结束后删除cook ...

  2. WebApi2官网学习记录---批量处理HTTP Message

    原文:Batching Handler for ASP.NET Web API 自定义实现HttpMessageHandler public class BatchHandler : HttpMess ...

  3. WebApi2官网学习记录---Html Form Data

    HTML Forms概述 <form action="api/values" method="post"> 默认的method是GET,如果使用GE ...

  4. WebApi2官网学习记录--HttpClient Message Handlers

    在客户端,HttpClient使用message handle处理request.默认的handler是HttpClientHandler,用来发送请求和获取response从服务端.可以在clien ...

  5. WebApi2官网学习记录--HTTP Message Handlers

    Message Handlers是一个接收HTTP Request返回HTTP Response的类,继承自HttpMessageHandler 通常,一些列的message handler被链接到一 ...

  6. WebApi2官网学习记录--- Authentication与Authorization

    Authentication(认证)   WebAPI中的认证既可以使用HttpModel也可以使用HTTP message handler,具体使用哪个可以参考一下依据: 一个HttpModel可以 ...

  7. WebApi2官网学习记录---单元测试

    如果没有对应的web api模板,首先使用nuget进行安装 例子1: ProductController 是以硬编码的方式使用StoreAppContext类的实例,可以使用依赖注入模式,在外部指定 ...

  8. WebApi2官网学习记录---Tracing

    安装追踪用的包 Install-Package Microsoft.AspNet.WebApi.Tracing Update-Package Microsoft.AspNet.WebApi.WebHo ...

  9. WebApi2官网学习记录---异常处理

    HttpResponseException 当WebAPI的控制器抛出一个未捕获的异常时,默认情况下,大多数异常被转为status code为500的http response即服务端错误. Http ...

随机推荐

  1. Resharper

    http://baike.baidu.com/link?url=H8DVtrvKV1Cg-Hrz82C6ZiJOUXbi_3BfoROe-RlHhctPna4-BFfglPh2OsR-KmCqRZ7_ ...

  2. cocos2dx 帧动画(iOS)

    植物大战僵尸的植物摇摆效果 //帧动画 Animation *animation = Animation::create(); Sprite *sprite = Sprite::create(&quo ...

  3. 使用 Nginx 来反向代理多个 NoderCMS

    Nginx ("engine x") 是一个高性能的HTTP和反向代理服务器,也是一个IMAP/POP3/SMTP服务器.Nginx是由Igor Sysoev为俄罗斯访问量第二的R ...

  4. grunt之dev-pro环境切换

    在项目开发过程中和发布阶段需要在开发环境(dev)和生产环境(pro)之间切换,静态文件引用的切换等等. 使用grunt要如何解决上述问题,这里提供一个案列供参考. 用到的grunt插件: 文件合并: ...

  5. 汇编语言中PTR的含义(转载)

    mov ax,bx ;是把BX寄存器“里”的值赋予AX,由于二者都是word型,所以没有必要加“WORD” mov ax,word ptr [bx];是把内存地址等于“BX寄存器的值”的地方所存放的数 ...

  6. javascript一些常用函数

    1.indexof 方法可返回某个指定的字符串值在字符串中首次出现的位置. 注释:indexOf() 方法对大小写敏感! 如果要检索的字符串值没有出现,则该方法返回 -1.  例 : 在本例中,我们将 ...

  7. php模板引擎技术简单实现

    用了smarty,tp过后,也想了解了解其模板技术是怎么实现,于是写一个简单的模板类,大致就是读取模板文件->替换模板文件的内容->保存或者静态化 tpl.class.php主要解析 as ...

  8. [Python 3.x 官方文档翻译]Whetting Your Appetite 欢迎您的使用

    If you do much work on computers, eventually you find that there’s some task you’d like to automate. ...

  9. PYTHON-进阶-ITERTOOLS模块

    PYTHON-进阶-ITERTOOLS模块小结 这货很强大, 必须掌握 文档 链接 pymotw 链接 基本是基于文档的翻译和补充,相当于翻译了 itertools用于高效循环的迭代函数集合 组成 总 ...

  10. 为什么针对XML的支持不够好?如何改进?

    为什么针对XML的支持不够好?如何改进? 物理文件是我们最常用到的原始配置的载体,最佳的配置文件格式主要由三种,它们分别是JSON.XML和INI,对应的配置源类型分别是JsonConfigurati ...