如何全局访问当前的 HttpRequestMessage 对象? [英] How to access the current HttpRequestMessage object globally?
问题描述
我有一个方法可以创建一个包含 Error 对象的 HttpResponseMessage,该对象将根据当前的请求媒体类型格式化程序返回.
I have a method which creates an HttpResponseMessage containing an Error object which will be returned based on the current request media type formatter.
目前,我对 XmlMediaTypeFormatter 进行了硬编码,但我希望能够在运行时找到当前请求 MediaTypeFormatter,但我无法访问当前请求对象,因为我的以下代码存在于单独的类库中.
Currently, I have hardcoded the XmlMediaTypeFormatter but I'd like to be able to find the current request MediaTypeFormatter at runtime but I don't have access to the current request object since my below code exists on a separate class library.
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
How to access the current HttpRequestMessage object globally? something like HttpContext.Current.Request
如果不可能,如何实现上述方法,使其知道应该为当前请求使用哪个格式化程序?
If impossible, how to implement the above method so that it knows which formatter it should be using for the current request?
推荐答案
这并非不可能,因为我最近才发现.它实际上是添加到当前HttpContext的Items属性中的(如果有的话)=[
It's not impossible as I have just recently found out. It's actually added into the Items property of the current HttpContext (if there is one) =[
HttpRequestMessage httpRequestMessage = HttpContext.Current.Items["MS_HttpRequestMessage"] as HttpRequestMessage
这是从 WebAPI v2 开始的.我不能确定以前的版本.
This is as of WebAPI v2 .. I cannot be sure of previous versions.
这篇关于如何全局访问当前的 HttpRequestMessage 对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!