如何全局访问当前的HttpRequestMessage对象

本文关键字:HttpRequestMessage 对象 何全局 访问 | 更新日期: 2023-09-27 18:14:52

我有一个方法,它创建了一个HttpResponseMessage,其中包含一个Error对象,该对象将根据当前请求媒体类型格式化器返回。

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

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

如果不可能,如何实现上面的方法,使它知道应该使用哪个格式化器为当前的请求?

如何全局访问当前的HttpRequestMessage对象

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

HttpRequestMessage httpRequestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage
编辑:

这是WebAPI v2。我不能确定以前的版本

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

稍微不同的是,我建议您研究一下错误响应的一些标准化工作,而不是自己发明。

例如:

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

你可以尝试用Autofac存档,例如

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生命周期

   builder.RegisterType<MyPrincipal>().As<IPrincipal>().InstancePerRequest();
相关文章:
  • 没有找到相关文章