简体   繁体   English

如何在WebApi + Odata项目中更改路由

[英]How to change route in WebApi+Odata project

I'm re-implementing WCF service and I choose to use WebAPI 2.2 + OData v4. 我正在重新实现WCF服务,并且选择使用WebAPI 2.2 + OData v4。 Problem I'm facing is that I need to have route which contains '_' and I'm unable to implement it. 我面临的问题是我需要包含“ _”的路由,但无法实现它。 Currently I have this: 目前我有这个:

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

and my WebApiConfig.cs looks like this: 我的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();
}

When I issue GET request I receive following error 当我发出GET请求时,出现以下错误

{ "Message": "No HTTP resource was found that matches the request URI ' http://localhost:12854/annotation_shared_with '.", "MessageDetail": "No type was found that matches the controller named 'annotation_shared_with'." {“” Message“:”未找到与请求URI'http:// localhost:12854 / annotation_shared_with '匹配的HTTP资源。“” MessageDetail“:”未找到与名为'annotation_shared_with'的控制器匹配的类型。“ } }

By default OData will search for annotation_shared_withController as defined in your EDM Model. 默认情况下的OData将搜索annotation_shared_withController在你的EDM模型中定义。 Since your controller is named AnnotationSharedWithController it will return 404 . 由于您的控制器名为AnnotationSharedWithController ,它将返回404

Renamaing your controller class will solve the issue. 重塑您的控制器类将解决此问题。 But you will end up with messy class names. 但是您最终会得到混乱的类名。

You can implement your own Routing Conventions, see Routing Conventions in ASP.NET Web API 2 Odata for more details 您可以实现自己的路由约定,有关更多详细信息,请参见ASP.NET Web API 2 Odata中的路由约定。

Hope it helps. 希望能帮助到你。

Your could use routing attributes to achieve this: 您可以使用路由属性来实现此目的:

  1. Using ODataRouteAttribute class: 使用ODataRouteAttribute类:

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM