2

我创建了一个“实用程序”控制器,它没有绑定到任何模型并且只包含未绑定的函数。
我希望能够通过如下网址调用它:
odata/Utilities/SomeMethod()

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

如何为“实用程序”创建自定义路线?

我努力了:

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

我也试过:

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

但是这两个都会引发错误:
“控制器'Utilities'中操作'SomeMethod'的路径模板'Utilities/SomeMethod()'不是有效的OData路径模板。找不到段'Utilities'的资源。”

4

2 回答 2

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());
    
于 2017-01-11T15:34:53.643 回答
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());

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

于 2017-01-10T13:28:16.677 回答