c# - OData 路由返回 404 Not Found

标签 c# asp.net-web-api odata

我已经开始在我的 WebAPI2 项目中包含 OData(目前托管在我的开发机器上的 IIS8 Express 中)。我的 OData 配置类如下所示:

public class ODataConfig
{
    private readonly ODataConventionModelBuilder modelBuilder;

    public ODataConfig()
    {
        modelBuilder = new ODataConventionModelBuilder();

        modelBuilder.EntitySet<Category>("Category");
    }

    public IEdmModel GetEdmModel()
    {
        return modelBuilder.GetEdmModel();
    }
}

然后我在 WebApiConfig 类中添加了以下内容:

ODataConfig odataConfig = new ODataConfig();

config.MapODataServiceRoute(
    routeName: "ODataRoute",
    routePrefix: "MyServer/OData",
    model: odataConfig.GetEdmModel(),
    defaultHandler: sessionHandler
);

从一个基本的 Controller 和一个 Action 开始,就像这样:

public class CategoryController : ODataController
{
    [HttpGet]
    public IHttpActionResult Get([FromODataUri] int key)
    {
        var entity = categoryService.Get(key);
        if (entity == null)
            return NotFound();

        return Ok(entity);
    }
}

然后,在我的 HttpClient 中,请求 url 如下所示: 我的服务器/OData/类别(10)

但是,我收到以下错误:

{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/MyServer/OData/Category(10)'.","MessageDetail":"No type was found that matches the controller named 'OData'."}

我在这里错过了什么?

编辑

如果我将 routePrefix 设置为 null 或 'odata' 并相应地更改我的请求 url,请求工作正常。所以这意味着我不能有像“myServer/odata”这样的路由前缀。

这是 OData 标准命名约定吗?如果是,它可以被覆盖吗?

最佳答案

这可能为时已晚,但对于任何其他最终来到这里的人来说......

我不认为问题出在 odata 上。也许您违反了默认路由,因为消息“未找到与名为‘OData’的 Controller 匹配的类型”表明 http://localhost/MyServer/OData/Category(10) 正在使用

进行路由
routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters

所以它正在寻找一个名为 ODataController 的 Controller ,其操作为“Category”。您需要将“localhost/MyServer”定义为应用路由的根目录。遗憾的是,我无法建议您如何做到这一点,但希望这能为您指明正确的方向。

关于c# - OData 路由返回 404 Not Found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26864434/

相关文章:

C# DataGridViewLinkCell 显示

asp.net-mvc-4 - 使用 Web Api 和结构图依赖注入(inject)

asp.net-web-api - Web Api - 使用 ApiExplorer 自动生成请求示例

odata - 如何获取已过滤的 OData 结果的计数?

c# - 如何在 C# 中的 foreach 循环中添加一个 where

c# - 访问 Web 应用程序数据库的批处理电子邮件过程的最佳方法

c# - 从 C# 环境向 powershell 脚本文件传递参数

asp.net-web-api - web api - 消息处理程序属性路由

java - 尝试使用 Java 将 OData $filter 解析为其名称-值对

oauth - 使用 BreezeJS OData 数据服务传递授权持有者 token