除非我添加尾部斜杠

时间:2016-05-25 04:52:02

标签: iis asp.net-web-api odata

我创建了一个虚拟项目来测试VS2015中的Odata,我遇到了与此问题中描述的问题完全相同的问题,我的代码大致相当于那里描述的内容。 Web API 2: OData 4: Actions returning 404

在添加尾部斜杠之前,对绑定函数的任何查询都会产生404错误。例如:

http://localhost:46092/odata/v1/Trips/Default.GetTripNameById - 404 http://localhost:46092/odata/v1/Trips/Default.GetTripNameById/ - 按预期工作

http://localhost:46092/odata/v1/Trips/Default.GetTripNameById(tripID=1)?$ select =姓名 - 404 http://localhost:46092/odata/v1/Trips/Default.GetTripNameById(tripID=1)/?$ select = Name - 按预期工作

这不应该发生,因为Microsoft文档从未提到需要使用尾部斜杠,他们的示例应该在没有它们的情况下工作。此外,这会破坏Swagger UI,它不会添加尾部斜杠,并在尝试进行任何查询时获取404。

这种行为可能是什么原因?如何在没有斜线的情况下使其工作,这似乎是正常的预期行为?

以下是我的代码段:

TripsController.cs:

    ...
    [HttpGet]
    public IHttpActionResult GetTripNameById(int tripID)
    {
        return Ok(DemoDataSources.Instance.Trips.AsQueryable().Where(t => t.ID == tripID.ToString()));
    }

WebApiConfig.cs:

public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.MapODataServiceRoute("odata", "odata/v1", GetEdmModel());

DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
        config.EnsureInitialized();
    }

    private static IEdmModel GetEdmModel()
    {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<Person>("People");
        builder.EntitySet<Trip>("Trips");

        builder.EntityType<Trip>().Collection.Function("GetTripNameById").Returns<string>().Parameter<int>("tripID");

        var edmModel = builder.GetEdmModel();
        return edmModel;
    }

1 个答案:

答案 0 :(得分:1)

事实证明,Visual Studio实际上忽略了Web.debug.config。

将此代码添加到web.config后,一切正常:

<system.webServer>
<handlers>
  <!-- the following line is required for correct handling of dots in URLs-->
  <add name="ApiURIs-ISAPI-Integrated-4.0"
     path="/odata/*"
     verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS"
     type="System.Web.Handlers.TransferRequestHandler"
     preCondition="integratedMode,runtimeVersionv4.0" />
  <!-- end line for handling of dots-->
</handlers>
</system.webServer>