具有自定义路由的OData v4未绑定功能

时间:2017-01-05 15:25:31

标签: asp.net-web-api odata asp.net-web-api-routing odata-v4

我创建了一个" Utilities"未绑定到任何模型且仅包含未绑定功能的控制器 我希望能够通过以下网址调用此信息:
的OData /实用工具/的someMethod()

现在我必须像下面这样称呼它:
odata / SomeMethod()

如何为"实用程序"?创建自定义路由?

我试过了:

[ODataRoutePrefix("Utilities")]
public class UtilitiesController : ODataController

我也尝试过:

[ODataRoute("Utilities/SomeMethod()"]
public string SomeMethod()

但这两个都会引发错误:
"路径模板' Utilities / SomeMethod()'在行动' SomeMethod'在控制器' Utilities'不是有效的OData路径模板。未找到该细分受众群的资源'公用事业'。"

2 个答案:

答案 0 :(得分:0)

您可以覆盖默认控制器选择器来实现此目的。您可以创建一个继承自DefaultHttpControllerSelector的新类:

public class CustomControllerSelector : DefaultHttpControllerSelector
{

    public override string GetControllerName(HttpRequestMessage request)
    {
        string controllerName = null;
        // I haven't tested this, but here you can decide whether you want to 
        //  route to your new controller or not
        if (request.ODataProperties().Path.PathTemplate == "~/UnboundFunction")
        {
            controllerName = "UtilitiesController";
        }
        else
        {
            controllerName = base.GetControllerName(request);
        }

        return controllerName;
    }
}

然后您可以像这样替换控制器选择器:

config.Services.Replace(typeof(IHttpControllerSelector), new CustomControllerSelector());

这使您可以选择在运行时为每个请求使用哪个控制器

答案 1 :(得分:0)

  1. 定义控制器类:

    public class UtilitiesController : ODataController
    {
        [System.Web.Http.HttpGet]
        [ODataRoute("SomeMethod")]
        public string SomeMethod()
        {
            // add your code
        }
    }
    
  2. 映射路线:

    var config = new HttpConfiguration();
    
    var modelBuilder = new ODataConventionModelBuilder();
    
    modelBuilder.Function("SomeMethod").Returns<string>();
    
    config.MapODataServiceRoute("ODataRoute", "odata/Utilities", modelBuilder.GetEdmModel());