OData路由返回404 Not Found

时间:2014-11-11 12:00:44

标签: 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
);

从一个基本控制器开始,只有一个动作,如下所示:

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中,请求网址如下所示:     MyServer的/的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或&#39; odata&#39;并相应地更改我的请求URL,请求正常。所以这意味着我不能拥有类似于&#39; myServer / odata&#39;的路由前缀。

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

2 个答案:

答案 0 :(得分:2)

这可能为时已晚,但对于其他任何人来说都是......

我不认为问题是odata。也许你正在违反默认路由,因为消息&#34;没有找到与名为&#39; OData&#39;&#34;建议http://localhost/MyServer/OData/Category(10) 正在使用

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

所以它正在寻找一个名为ODataController的控制器,其中包含一个动作&#34;类别&#34;。你需要定义&#34; localhost / MyServer&#34;作为应用路由的根。不幸的是,我无法建议你如何做到这一点,但希望这可以指出你正确的方向。

答案 1 :(得分:1)

我一直在使用Web API项目中默认包含的相同WebApiConfig.Register()方法,并使用以下方法传递:

var builder = new ODataConventionModelBuilder();

// OData entity sets..
builder.EntitySet<Seat>("Seats");
builder.EntitySet<Table>("Tables");

// Configure the Route
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());

第一个参数是一个友好的名字,第二个是你要追求的名字!您可以将其更改为您想要的任何内容。

更新:如果您使用的是OData V4,则路由初始化如下:

config.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());

如果您正在使用V4,现在可以使用属性进行基于方法的路由(想想南希风格)

您可以在OWIN启动类或Global.asax中使用它。无论哪种方式都适合我。

参考:http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v3/creating-an-odata-endpoint