未找到与MVC 404的OData v4操作冲突



当我升级到Odata v4时,所有在v3中工作的操作现在都会出现404未找到错误:

[HttpException]: The controller for path /odata/MyModel/CheckStatus was not found or does not implement IController.
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)

我的代码如下:

WebApiConfig:

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
...
config.MapODataServiceRoute(
    routeName: "OData",
    routePrefix: "odata",
    model: GetModel(),
    batchHandler: new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
    config.AddODataQueryFilter();

GetModel:

builder.EntityType<MyModel>().Collection.
Action("CheckStatus").Parameter<IEnumerable<EntityStatus<MyModel>>>("modelStatus");
...

ODataController:

public async Task<IHttpActionResult> CheckStatus([FromBody] IEnumerable<EntityStatus<MyModel>> modelStatus)
...

其中EntityStatus是一个泛型类,如下所示:

public class EntityStatus<T> where T : class
{
    [Key, Column(Order = 0)]
    public string Status { get; set; }
    [Key, Column(Order = 1)]
    public string Original { get; set; }
    public T Model { get; set; }
}

在Ajax调用中:

var url = "/odata/MyModel/CheckStatus";
$.ajax({
    url: url,
    ...

我尝试过添加命名空间、修改web.config和使用OdataRoute,但都没有成功。你能帮我绕过上面显示的这些错误吗?

要了解所有OData 4操作"404未找到"错误,只需将Web.config中的模块部分替换为以下内容:

<modules runAllManagedModulesForAllRequests="true"></modules>

我在某处读到这不是一个好的解决方案。幸运的是,它现在正在工作。

如果您能与我分享您对此解决方案的经验,我将非常高兴。

最新更新