关于c#:如何全局访问当前的HttpRequestMessage对象?

How to access the current HttpRequestMessage object globally?

我有一个创建包含错误对象的HttpResponseMessage的方法,该对象将根据当前请求媒体类型格式化程序返回。

目前,我已经对XmlMediaTypeFormatter进行了硬编码,但是我希望能够在运行时找到当前请求MediaTypeFormatter,但是由于下面的代码存在于单独的类库中,因此我无法访问当前请求对象。

1
2
3
4
5
6
7
8
9
10
11
12
private HttpResponseMessage Create(HttpStatusCode statusCode, string errorCode, string errorMessage)
{
    var result = new HttpResponseMessage(statusCode)
        {
            Content = new ObjectContent<Error>(new Error()
            {
                Code = errorCode,
                Message = errorMessage
            }, new XmlMediaTypeFormatter())
        };
    return result;
}

如何全局访问当前的HttpRequestMessage对象? 像HttpContext.Current.Request之类的东西

如果不可能,如何实现上述方法,以便它知道当前请求应使用哪个格式化程序?


正如我最近发现的那样,这并非不可能。它实际上已添加到当前HttpContext的Items属性中(如果有的话)= [

1
HttpRequestMessage httpRequestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage

编辑:

这是从WebAPI v2开始的版本。我不确定以前的版本。


您可以尝试使用Autofac对其进行归档,例如

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class MyPrincipal : IPrincipal
    {
        private readonly IPrincipal principal_;

        public MyPrincipal(ILifetimeScope scope)
        {
            if (scope.Tag == null || scope.Tag != MatchingScopeLifetimeTags.RequestLifetimeScopeTag)
            {
                throw new Exception("Invalid scope");
            }

            principal_ = scope.Resolve<HttpRequestMessage>().GetRequestContext().Principal;
        }
}

可以使用InstancePerRequest生存期注册该类。

1
   builder.RegisterType<MyPrincipal>().As<IPrincipal>().InstancePerRequest();

Web API团队为什么不使用他们的CreateResponse方法来做?使其成为Controller的扩展方法。这样,您仍然可以将代码保存在单独的类库中,但是您的方法将可以访问控制器实例,因此可以访问所有配置信息。

另外,我建议您研究一些针对错误响应的标准化工作,而不要自己发明。

例如。:

  • http://www.mnot.net/blog/2013/05/15/http_problem
  • http://tools.ietf.org/html/draft-nottingham-http-problem-03
  • https://github.com/blongden/vnd.error