如何在全球范围内访问当前的Htt prequestMessage对象吗? [英] How to access the current HttpRequestMessage object globally?

查看:150
本文介绍了如何在全球范围内访问当前的Htt prequestMessage对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有它创建了一个方法的Htt的$ P $含有将根据当前请求的媒体类型格式返回一个错误的对象psponseMessage。

I have a method which creates an HttpResponseMessage containing an Error object which will be returned based on the current request media type formatter.

目前,我已经很难codeD的XmlMediaTypeFormatter,但我希望能够找到在运行当前请求MediaTypeFormatter但因为我下面code的存在,我没有访问当前请求对象在一个单独的类库。

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;
}

如何访问当前的Htt prequestMessage全球反对呢?像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的相关文件属性(如果有的话)= [

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的。我不能肯定previous版本。

This is as of WebAPI v2 .. I cannot be sure of previous versions.

这篇关于如何在全球范围内访问当前的Htt prequestMessage对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆