Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/325.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在webapi中注入请求ID_C#_Asp.net Web Api2 - Fatal编程技术网

C# 在webapi中注入请求ID

C# 在webapi中注入请求ID,c#,asp.net-web-api2,C#,Asp.net Web Api2,我想在处理请求的整个过程中维护一个ID(Guid.NewGuid()就足够了),这样以后我就可以检查给定ID的日志。我还将在响应头(和消息)中向调用方返回ID。如果出现错误,它们会有一个引用 首先,我在应用程序的Global.asaxapplication\u BeginRequest()方法中这样做,在该方法中,我将ID放入HttpContext.Current.Items集合中 protected void Application_BeginRequest(object sender, Ev

我想在处理请求的整个过程中维护一个ID(
Guid.NewGuid()
就足够了),这样以后我就可以检查给定ID的日志。我还将在响应头(和消息)中向调用方返回ID。如果出现错误,它们会有一个引用

首先,我在应用程序的Global.asax
application\u BeginRequest()
方法中这样做,在该方法中,我将ID放入
HttpContext.Current.Items
集合中

protected void Application_BeginRequest(object sender, EventArgs e)
{
    var context = HttpContext.Current;
    if (context != null)
    {
        var reqguid = Guid.NewGuid().ToString("D");
        context.Items.Add("sessionid", reqguid);
    }
}
这在以前的应用程序中运行得很好,但我觉得在“现代”Web API应用程序中使用
HttpContext
有点不确定

然后我转向动作过滤器,因为很明显,这是Web API的关键

public class ManageRequestHeadersFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        actionContext.Request.Properties.Add("sessionid", Guid.NewGuid().ToString("D"));
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        var sessionId = actionExecutedContext.Request.Properties["sessionid"].ToString();
        if (sessionId != null)
        {
            actionExecutedContext.Response.Headers.Add("App-Session-Id", sessionId);
        }
    }
}
...
config.Filters.Add(new ManageRequestHeadersFilter());
这也正常工作,直到我想进入
ApiController
构造函数中的
Request
对象,将helper属性设置为ID。由于控制器构造函数在过滤器之前运行,
Request
对象为空。同样,我可能会使用
HttpContext.Current
方式,但这超出了过滤器的用途

我还想过使用依赖注入(已经在使用Autofac)将ID注入构造函数,这同样有效,但现在我做的事情有点倒退,这让我最初的思路感到奇怪

我的感觉是,将ID作为控制器构造函数参数传入最终将是赢家,因为在进行单元测试时,无论如何我都不应该依赖任何HTTP


是否已经有了最佳实践?

使用
HttpContext
有什么问题?它是ASP.NET中最基本的类之一。即使对于单元测试,它也可以被模仿掉。