【问题标题】:Alternative to HttpRequestMessage SetContext methodHttpRequestMessage SetContext 方法的替代方法
【发布时间】:2017-04-04 21:11:30
【问题描述】:

我有来自 codeplex 的这段代码

private async Task ExecuteChangeSet(
        ChangeSetRequestItem changeSet,
        IList<ODataBatchResponseItem> responses,
        CancellationToken cancellation)
{
        ChangeSetResponseItem changeSetResponse;

        // Create a new ShoppingContext instance, associate it with each of the requests, start a new
        // transaction, execute the changeset and then commit or rollback the transaction depending on
        // whether the responses were all successful or not.
        using (ShoppingContext context = new ShoppingContext())
        {
            foreach (HttpRequestMessage request in changeSet.Requests)
            {
                request.SetContext(context);
            }

完整的示例代码可以在here找到。 我下载了这个项目,它使用的是 .net framework 4.5 但在 .NET Framework 4.6.1 中不再存在 SetContext 方法 我想知道如何在框架版本 4.6.1 中实现相同的功能? 我基本上是在创建一个 OData V3 服务,它将托管在 IIS 中。

【问题讨论】:

    标签: asp.net-web-api odata


    【解决方案1】:

    您可以创建自己的功能来设置上下文并在需要时检索它,使用 HttpRequestMessage 扩展,例如:

    示例类:

    public static class HttpRequestMessageExtensions
    {
         private const string Context = "ShoppingContext";
         public static void SetContext(this HttpRequestMessage request, ShoppingContext context)
        {
            request.Properties[Context] = context;
        }
    
        public static ShoppingContext GetContext(this HttpRequestMessage request)
        {
            object context;
            if (request.Properties.TryGetValue(Context, out context))
            {
                return (ShoppingContext) context;
            }
            return null;
        }
    }
    

    用法:

    //Setting context
    request.SetContext(context);
    //reading context
    var context = request.GetContext();
    

    【讨论】:

    • 我实际上拥有该代码,因为它是示例代码的一部分。我实际上想知道它的用法。我觉得我不明白?您提到的用法实际上与我上面发布的代码相同。你能详细说明你的答案吗?
    • 好吧,这实际上是我的错,我在扩展类中有不同的命名空间。另一个批处理类具有 iPOSServiceV3.Extension 命名空间,而扩展具有 iPOSServiceV3.Extensions 命名空间。更正名称空间后,现在一切正常。
    • 其实,看到这个github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/… 给了我一个想法,我的代码应该可以工作。
    猜你喜欢
    • 2012-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-08
    • 2011-03-03
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    相关资源
    最近更新 更多