Web Api Odata无法正常工作

时间:2013-03-13 17:48:25

标签: asp.net-web-api odata

我创建了一个Web Api OData控制器,并尝试直接查看它,但它无法正常工作。

WebApiConfig config

 public static void Register(HttpConfiguration config)
    {
      config.Routes.MapODataRoute("odata", "odata", GetEdmModel());
      config.Routes.MapHttpRoute(
          name: "DefaultApi",
          routeTemplate: "api/{controller}/{id}",
          defaults: new { id = RouteParameter.Optional }
      );
    }

    public static IEdmModel GetEdmModel()
    {
      ODataModelBuilder builder = new ODataConventionModelBuilder();
      builder.EntitySet<Customer>("Customers");
      builder.Namespace = "PackageManager.Models";
      return builder.GetEdmModel();
    }
在App开始调用注册时

WebApiConfig.Register(GlobalConfiguration.Configuration);

Api控制器:

public class CustomersController : EntitySetController<Customer, string>
  {
    NorthwindDbContext _Context = new NorthwindDbContext();

    [Queryable]
    public override IQueryable<Customer> Get()
    {
      return _Context.Customers;
    }

    protected override void Dispose(bool disposing)
    {
      base.Dispose(disposing);
           _Context.Dispose();
    }
  }

尝试访问: 本地主机:2375 /的OData /客户

然后总是收到错误:

无法找到资源。

2 个答案:

答案 0 :(得分:-1)

只需在system.webServer \ handler:

上添加以下web.config
<add name="ApiURIs-ISAPI-Integrated-4.0" path="*" verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

或替换

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*" verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

(不同 - 路径属性中的一个点)

答案 1 :(得分:-1)

@Parwej - 尝试在webapi.config中编写以下代码,而不是代码。另外,请确保您的网址中包含正确的大小写,因为Odata网址区分大小写。并且不要忘记在控制器中使用System.Web.Http.OData而不是System.Web.Odata。这应该有用。

public static void Register(HttpConfiguration config)
{
  ODataModelBuilder builder = new ODataConventionModelBuilder();
  builder.EntitySet<Customer>("Customers");
  config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());
}