C# 非静态字段、方法或属性“HttpContext.Request"需要对象引用 [英] C# An object reference is required for the non-static field, method, or property 'HttpContext.Request'
问题描述
我正在尝试创建一个通用工厂类来调用 WCF 并注入一些标头.在这个类中,我试图读取 HTTP 标头属性.
I am trying create a common factory class to call WCF and to inject some headers. In this class I am trying to read the HTTP Header properties.
using System.ServiceModel;
using System.ServiceModel.Channels;
using ServiceReference;
using Microsoft.AspNetCore.Http;
namespace Service
{
public class ServiceFactory
{
public static ServiceClient Create()
{
ServiceProxy service = new ServiceProxy();
string userName = HttpContext.Request.Headers["AUTH_USERNAME"];
string authenricationType = HttpContext.Request.Headers["AUTH_TYPE"];
using (new System.ServiceModel.OperationContextScope((System.ServiceModel.IClientChannel)service.InnerChannel))
{
HttpRequestMessageProperty requestMessage = new HttpRequestMessageProperty();
requestMessage.Headers["AUTH_USERNAME"] = userName;
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
requestMessage.Headers["AUTH_TYPE"] = authenricationType;
OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessage;
}
return service;
}
}
}
但是我收到一个编译错误 非静态字段、方法或属性 'HttpContext.Request' 需要一个对象引用.因为我不是从静态方法或一堂课这是怎么发生的.任何帮助将不胜感激.
But I get a compile error as "An object reference is required for the non-static field, method, or property 'HttpContext.Request'. Since I am not calling from a Static method or a class how this could happen. Any help would be highly appreciated.
谢谢.
推荐答案
HttpContext.Request
不起作用,因为它试图访问实例属性,就像它是静态属性一样.HttpContext.Current.Request
应该可以工作,假设到那时上下文已经与线程相关联
HttpContext.Request
won't work, because that's trying to access an instance property as if it were a static property. HttpContext.Current.Request
should work, assuming the context has been associated with the thread by that point
HttpContext.Request 和 Request 的区别
这篇关于C# 非静态字段、方法或属性“HttpContext.Request"需要对象引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!