Add a function or parameter to OData controller

2019-08-25 02:57发布

I'm using ASP.NET Boilerplate framework for ASP.NET Core. I have the boilerplate OData controllers as per https://aspnetboilerplate.com/Pages/Documents/OData-AspNetCore-Integration.

I want to support passing of a custom parameter in either the GET method or in a custom OData function. How do I do this in the AbpODataEntityController?

Regards, David

1条回答
Luminary・发光体
2楼-- · 2019-08-25 03:51

Looking at the source code, it looks like they are using the standard "Microsoft.AspNet.OData" Version="7.1.0".

So you probably have a place where you set up your EdmModel. You should create a function in your controller like this:

// odata/Tenants/Default.IsDomainAvailable('<domain name here>')
[HttpGet]
public IActionResult IsDomainAvailable([FromODataUri] string domainName)
{
    if (!ModelState.IsValid) return BadRequest();
    try
    {
        var item = _unitOfWork.Tenants
            .FindByHostName(domainName)
            .FirstOrDefault();

        if (item == null) 
            return Ok(string.Format("{0} is available", domainName));

        return StatusCode(StatusCodes.Status409Conflict, string.Format("{0} is not available", domainName));
    }
    catch (Exception ex)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, ex.Message);
    }
}

Then you can just declare a function in your EDM model builder like this:

private void BuildFunctions(ODataModelBuilder builder)
{
    builder.EntityType<TenantDTO>().Collection
        .Function("IsDomainAvailable")
        .Returns<IActionResult>()
        .Parameter<string>("domainName");
}

And call it from Postman like this:

odata/Tenants/Default.IsDomainAvailable('<domain name here>')

Hope this helps.

查看更多
登录 后发表回答