替代HttpRequestMessage SetContext方法

时间:2017-04-04 08:34:02

标签: asp.net-web-api odata

我有来自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中实现相同的功能? 我基本上创建了一个将在IIS中托管的OData V3服务。

1 个答案:

答案 0 :(得分:0)

您可以创建自己的功能来设置上下文并在需要的地方检索它,使用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();