2016-11-10 24 views
0

我正在重新实施WCF服务,并选择使用WebAPI 2.2 + OData v4。 我面临的问题是我需要有包含'_'的路由,我无法实现它。 目前我有这样的:如何在WebApi + Odata项目中更改路线

public class AnnotationSharedWithController : ODataController 
{ 
    ... 
    [EnableQuery] 
    public IQueryable<AnnotationSharedWith> Get() 
    { 
     return _unitOfWork.AnnotationSharedWith.Get(); 
    } 
    ... 
} 

和我WebApiConfig.cs看起来是这样的:

public static void Register(HttpConfiguration config) 
{ 
    config.MapODataServiceRoute("webservice",null,GenerateEdmModel()); 
     config.Count(); 
} 

private static IEdmModel GenerateEdmModel() 
{ 
    var builder = new ODataConventionModelBuilder(); 
    builder.EntitySet<AnnotationSharedWith>("annotation_shared_with"); 
     return builder.GetEdmModel(); 
} 

当我发出GET请求我收到以下错误

{ “消息”:“找不到与请求URI 'http://localhost:12854/annotation_shared_with'。“,”MessageDetail“: 匹配的HTTP资源”找不到与名为的控制器相匹配的类型'annotation_shared_with'。“ }

回答

0

你可以使用路由属性来实现这一目标:

  1. 使用ODataRouteAttribute类:

    public class AnnotationSharedWithController : ODataController 
    { 
        [EnableQuery] 
        [ODataRouteAttribute("annotation_shared_with")] 
        public IQueryable<AnnotationSharedWith> Get() 
        { 
         //your code 
        } 
    } 
    
  2. 使用ODataRoutePrefixAttributeODataRouteAttribute类:

    [ODataRoutePrefixAttribute("annotation_shared_with")] 
    public class AnnotationSharedWithController : ODataController 
    { 
        [EnableQuery] 
        [ODataRouteAttribute("")] 
        public IQueryable<AnnotationSharedWith> Get() 
        { 
         //your code 
        } 
    } 
    
0

默认情况下,OData将按您的EDM模型中的定义搜索annotation_shared_withController。由于您的控制器被命名为AnnotationSharedWithController,它将返回404

Renamaing你的控制器类将解决这个问题。但你最终会遇到混乱的类名。

您可以实现自己的路由约定,请参见 Routing Conventions in ASP.NET Web API 2 Odata更多细节

希望它能帮助。