【发布时间】:2020-06-22 18:09:47
【问题描述】:
如你所见,我有这门课:
public class mybaseclass
{
public string token = "";
private readonly HttpContextAccessor iHTTP;
public mybaseclass([FromServices]HttpContextAccessor IHTTP)
{
//this.httpContext = httpContext;
iHTTP = IHTTP;
}
public mybaseclass()
{
}
protected Task<HttpRequestMessage> CreateHttpRequestMessageAsync(CancellationToken cancellationToken)
{
// var t = null;
try
{
// iHTTP.HttpContext.Request.Cookies[key]
var t = iHTTP.HttpContext.Request.Cookies["Authorization"];
if (t == null)
{
token = t;
}
}
catch(Exception aaa)
{
}
var msg = new HttpRequestMessage();
// SET THE BEARER AUTH TOKEN
msg.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
return Task.FromResult(msg);
}
}
并且这个类在这个类中被调用:
public partial class Default1Client : mybaseclass, IDefault1Client
{
private string _baseUrl = "";
private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings;
public Default1Client(string baseUrl)
{
BaseUrl = baseUrl;
_settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(CreateSerializerSettings);
}
// other part of code
}
我的问题是当我调用 Default1Client 时,该类调用了没有任何参数的 mybaseclass 构造函数,但我需要调用带有 httpcontextaccessor 的构造函数
【问题讨论】:
-
您究竟是如何创建
Default1Client的实例的?是被注入还是你在使用new? -
@JohnWu 它被注入到我的控制器中,并且我在启动文件中设置了注入
-
那么你是如何填充
baseUrl的呢?你能告诉我们这样做的代码/配置吗? -
@JohnWu public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); // services.AddScoped
(); services.AddScoped (provider => { return new Default1Client("localhost:44381"); }); services.TryAddSingleton (); services.AddHttpContextAccessor(); }
标签: c# .net class constructor