41

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

目前,我已经对 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

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

4

3 回答 3

82

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

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

编辑:

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

于 2013-11-04T20:57:18.800 回答
1

Why not do what the Web API team have done with their CreateResponse method? Make it an extension method of Controller. That way you can still have the code in a separate class library, but your method will have access to the controller instance and therefore all the Configuration information.

And on a slightly different note, I would suggest you look into some of the standardization efforts for error responses rather than inventing your own.

e.g.:

于 2013-05-21T14:33:52.047 回答
1

您可以尝试使用 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();
于 2019-07-22T06:30:43.497 回答