c#-尽管使用System.Web.Odata.Extensions,“’HttpRequestMessageProperties’不包含’PathHandler’的定义”
作者:互联网
我当前正在学习如何使用MS’s ASP.NET web API guide 创建OData服务.在“助手”部分中,尝试获取HttpRequestMessage.ODataProperties().PathHandler或… Model字段会引发上述错误.根据MS’s documentation,导入System.Web.OData.Extensions应该正确.
对于Odata.Client使用6.13.0,对于Odata.Core使用7.0.0.
相关代码,基本上与Web api指南为1:1:
using Microsoft.OData;
using Microsoft.OData.UriParser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http.Routing;
using System.Web.OData.Extensions;
namespace WebApiGuide {
public static class Helpers
{
public static TKey GetKeyFromUri<TKey>(HttpRequestMessage Request, Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException("uri");
}
var urlHelper = Request.GetUrlHelper() ?? new UrlHelper(Request);
string serviceRoot = urlHelper.CreateODataLink(
Request.ODataProperties().RouteName,
Request.ODataProperties().PathHandler, new List<ODataPathSegment>());
var odataPath = Request.ODataProperties().PathHandler.Parse(
Request.ODataProperties().Model,
serviceRoot, uri.LocalPath);
var keySegment = odataPath.Segments.OfType<KeyValuePathSegment>().FirstOrDefault();
if (keySegment == null)
{
throw new InvalidOperationException("The link does not contain a key");
}
var value = ODataUriUtils.ConvertFromUriLiteral(keySegment.Value, ODataVersion.V4);
return (TKey)value;
}
}
}
编辑:如果它使问题更加具体,则System.Web.OData.Routing中的KeyValuePathSegment也有相同的问题
解决方法:
对于其他出于相同原因而在此处结束的人,这是我的代码(显然keySegment也已更改,并且Value包含已转换的对象):
public static TKey GetKeyFromUri<TKey>(HttpRequestMessage request, Uri uri)
{
if (uri == null)
{
throw new ArgumentNullException(nameof(uri));
}
var urlHelper = request.GetUrlHelper() ?? new UrlHelper(request);
var serviceRoot = urlHelper.CreateODataLink(request.ODataProperties().RouteName, request.GetPathHandler(), new List<ODataPathSegment>());
var odataPath = request.GetPathHandler().Parse(serviceRoot, uri.LocalPath, request.GetRequestContainer());
var keySegment = odataPath.Segments.OfType<KeySegment>().FirstOrDefault();
if (keySegment?.Keys?.FirstOrDefault() == null)
{
throw new InvalidOperationException("The link does not contain a key.");
}
return (TKey)keySegment.Keys.First().Value;
}
标签:odata,visual-studio-2017,asp-net,c 来源: https://codeday.me/bug/20191111/2017952.html