.NET MVC 5 OData自定义操作绑定到版本的实体

时间:2017-10-29 04:37:17

标签: asp.net-mvc odata

在.NET MVC 4/5中,我可以创建绑定到实体的自定义操作。 e.g。

var builder = new ODataConventionModelBuilder();
...
var testAction = builder.EntityType<MyEntity>().Action("Test");
testAction.Returns<bool>();
testAction.Parameter<int>("testParameter");
...
return builder.GetEdmModel()

但是如何使用VersionedODataModelBuilder实现绑定到实体的版本化自定义操作? e.g。

var builder = new VersionedODataModelBuilder(config)
{
    ModelConfigurations =
    {
        new TestModelConfiguration()
    }
    ...
    // BAD: property EntityType does not exist on the builder object.
    var testAction = builder.EntityType<MyEntity>().Action("Test"); 
};

1 个答案:

答案 0 :(得分:0)

我能够使用以下方法在路线上成功创建自定义动作和自定义功能。

我需要将我的问题代码添加到TestModelConfiguration.cs中,这使得ODataModelBuilder对象可用。

的web.config:

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

TestModelConfiguration.cs:

private EntityTypeConfiguration<RunViewModel> ConfigureCurrent(ODataModelBuilder builder)
{
    var pingFunction = builder.EntityType<RunViewModel>().Function("Ping");
    pingFunction.Returns<bool>();
    pingFunction.Parameter<int>("test");
    pingFunction.Namespace = "Function";

    var pongAction = builder.EntityType<RunViewModel>().Action("Pong");
    pongAction.Returns<bool>();
    pongAction.Parameter<int>("test");
    pongAction.Namespace = "Action";

TestController.cs:

public class RunController : BaseODataController
{
    [HttpGet]
    [ODataRoute("Test({key})/Function.Ping(test={test})")]
    public bool Ping([FromODataUri] int key, int test)
    {
        return true;
    }

    [HttpPost]
    [ODataRoute("Test({key})/Action.Pong")]
    public IHttpActionResult Pong([FromODataUri] int key, ODataActionParameters parameters)
    {
        return Ok(true);
    }