【问题标题】:How to change route in WebApi+Odata project如何在 WebApi+Odata 项目中更改路由
【发布时间】:2016-11-10 15:02:50
【问题描述】:

我正在重新实现 WCF 服务并选择使用 WebAPI 2.2 + OData v4。 我面临的问题是我需要包含“_”的路线,但我无法实现它。 目前我有这个:

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 请求时,我收到以下错误

{ "Message": "没有找到与请求 URI 匹配的 HTTP 资源 'http://localhost:12854/annotation_shared_with'.", "MessageDetail": “没有找到与名为的控制器匹配的类型 'annotation_shared_with'。” }

【问题讨论】:

    标签: c# asp.net-web-api2 odata


    【解决方案1】:

    您可以使用路由属性来实现此目的:

    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
          }
      }
      

    【讨论】:

      【解决方案2】:

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

      重命名您的控制器类将解决该问题。但是你最终会得到混乱的类名。

      您可以实现自己的路由约定,请参阅 Routing Conventions in ASP.NET Web API 2 Odata了解更多详情

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 2014-03-01
        • 1970-01-01
        • 2018-01-19
        • 2023-03-04
        • 1970-01-01
        • 1970-01-01
        • 2014-07-26
        • 2020-04-26
        • 2023-03-27
        相关资源
        最近更新 更多