替代HttpRequestMessage SetContext方法
问题描述:
我有CodePlex从替代HttpRequestMessage SetContext方法
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框架4.5 ,但在.NET Framework 4.6.1中,SetContext方法不再存在 我想知道如何在框架版本4.6.1中实现相同? 我基本上创建了一个OData V3服务,它将在IIS中托管。
答
您可以设置背景下创建自己的功能去和检索需要的地方,用HttpRequestMessage扩展,如:
Example类:
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();
我实际上有代码,因为它是示例代码的一部分。我真的很想知道它的用法。 我不觉得我明白吗?您提到的用法实际上与我在上面发布的代码相同。你能详细说明你的答案吗? – Learning
确定这是我的错,我在扩展类中有不同的名称空间。另一个批处理类具有iPOSServiceV3.Extension名称空间,而扩展名具有iPOSServiceV3.Extensions名称空间。现在纠正名称空间后,它的所有工作都很好。 – Learning
其实,看到这个https://github.com/ASP-NET-MVC/aspnetwebstack/blob/master/src/System.Web.Http/HttpRequestMessageExtensions.cs给了我一个想法,我的代码应该工作。 – Learning