【问题标题】:How to fix error 406 after returning from OData controller从 OData 控制器返回后如何修复错误 406
【发布时间】:2016-03-07 01:22:47
【问题描述】:

我正在寻找一种将 OData 控制器与 ASP.NET MVC4 Web.API 一起使用的方法

路由已在应用程序开始使用中注册

using Microsoft.Data.Edm;
using System.Web.Http;
using System.Web.Http.OData.Builder;
public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            config.Routes.MapODataRoute("odata", "api", GetEdmModel());
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );
            config.Formatters.Remove(config.Formatters.XmlFormatter);
        }

        static IEdmModel GetEdmModel()
        {
            ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
            return builder.GetEdmModel();

        }
 }}

OData 控制器:

using System.Web.Http;
using System.Web.Http.OData;
using System.Web.Http.OData.Query;
using System.Collections;

public class ODController : ODataController
{

    public class Poco
    {
        public int id { get; set; }
        public string name { get; set; }
        public string type { get; set; }
    }

    public IEnumerable Get(ODataQueryOptions queryOptions)
    {
        return new Poco[] {
    new Poco() { id = 1, name = "one", type = "a" },
    new Poco() { id = 2, name = "two", type = "b" },
    new Poco() { id = 3, name = "three", type = "c" }
};
    }

访问 url http://localhost:52216/admin/API/OD 返回 406 Not accepted 错误。 调试器显示控制器被命中。从控制器返回后发生错误。 如何解决这个问题,以便 OData 控制器可以在 MVC4 的 Web API 中使用?

【问题讨论】:

  • 1) 您确定需要using System.Web.Http.OData; 而不是using System.Web.OData;? OData V4 需要using System.Web.OData;。参见the example的控制器代码。 2)此外,您必须在GetEdmModel 行return builder.GetEdmModel(); 之前填写builder。请参阅同一示例中的WebApiConfig.cs 的代码。 3)你应该使用AsQueryable()并将IEnumerable替换为IQuerable<Poco>。
  • 谢谢。我能够解决这些问题。您指出的样本使用硬编码类型。数据列是在运行时根据用户选择打开 jqgrid 表之前定义的。看起来 MVC OData 需要在应用程序启动时定义类型才能创建模型。所以不能使用 OData。数据我会继续使用jqgrid原生的json格式。

标签: asp.net-mvc asp.net-mvc-4 asp.net-web-api odata asp.net-mvc-routing


【解决方案1】:

我认为您将 webapi 和 webapi 混合用于 odata。最好先阅读samples and tutorials。

根据您的提及,我无法理解您为什么期望 OData 可以基于一个空的 Edm 模型序列化 fly POCO 列表。

请试试这个:

使用你的 POCO 类来构建模型

ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Poco>("Do");
return builder.GetEdmModel();

确保控制器类命名约定。应该是[EntitySetName] + "Controller"

删除 Web API 路由。

config.Routes.MapHttpRoute(..);

然后,请求 Uri 应该返回你想要的。谢谢。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-10
    • 1970-01-01
    • 2016-03-30
    • 2016-05-21
    相关资源
    最近更新 更多