C#非静态字段,方法或属性'HttpContext.Request'需要对象引用 [英] C# An object reference is required for the non-static field, method, or property 'HttpContext.Request'

查看:1187
本文介绍了C#非静态字段,方法或属性'HttpContext.Request'需要对象引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个通用工厂类来调用WCF并注入一些标头。在此类中,我尝试读取HTTP Header属性。

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屋!

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