.NET7下Odata基础配置
依赖包 Microsoft.AspNetCore.OData Microsoft.Data.Services
1.Program
//注入OData,启动一些常规linq过滤方法支持
builder.Services.AddControllers().AddOData(options => options.AddRouteComponents("v1", GetEdmModel()).Filter().Select().Expand());
static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new();
builder.EntitySet<Address>("AddRess");
return builder.GetEdmModel();
}
//swagger配置
builder.Services.AddSwaggerGen(options =>
{
options.OperationFilter<ODataParameterAttributeFilter>();
});
2.ODataParameterAttributeFilter
照搬这里,其实这里反而是最重要的,我在自己尝试拼装语法的时候总是不成功并且没有提示。
.Net Core之OData - shadowxs - 博客园 (cnblogs.com)
Odata的使用——规范函数_odata contains_慕沐.的博客-CSDN博客
3.Controller
[ApiController]
[Route("/[controller]/")]
public class HomeController : ODataController
{
[HttpGet, EnableQuery]
//不要加FromODataUri 这玩意接的参数有毒
public SingleResult<Address> Get( int Id)
{
var result = new List<Address>() { new() { City = "CD", Street = "HG", Id = 1 } };
return SingleResult.Create(result.AsQueryable());
}
[HttpPost, EnableQuery]
public async Task<IActionResult> Post([FromBody] Address address)
{
//add logic
return Created(address);
}
[HttpPut, EnableQuery]
public async Task<IActionResult> Patch(int Id, Delta<Address> newAddress)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var existingAddress = new List<Address>().FirstOrDefault(s => s.Id == Id);
if (existingAddress == null)
{
return NotFound();
}
newAddress.Patch(existingAddress);
try
{
//save
}
catch (Exception ex)//DbUpdateConcurrencyException
{
if (!NoteExists(Id))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(existingAddress);
}
[HttpDelete, EnableQuery]
public async Task<IActionResult> Delete( int Id)
{
var existingAddress = new List<Address>().FirstOrDefault(s => s.Id == Id);
if (existingAddress == null)
{
return NotFound();
}
//remove
return StatusCode(StatusCodes.Status204NoContent);
}
private bool NoteExists(int Id)
{
return true;
}
}