簡體   English   中英

WebApi 在沒有 ActionResult 的情況下返回 HTTP 狀態代碼 400、401 等

[英]WebApi return HTTP status code 400, 401 etc without ActionResult

如果方法不返回 ActionResult,是否可以返回特定的 http 狀態?

示例:

public async Task<IQueryable<ModuleView>> Get()

我無法返回 ActionResult<IQueryable> 因為 ActionResult 不適用於 OData 和 EnableQueryAttribute,屬性未觸發...在屬性中我有:

override IQueryable ApplyQuery(IQueryable queryable, ODataQueryOptions queryOptions)

但我想返回 BadRequest、Unauthorized 等...

有可能的?

編輯:我有帶有 OData 8.0.10 的 .net 6 web api。

我正在嘗試這樣的事情:

    [HttpGet]
    public async Task<ActionResult<IQueryable<ModuleView>>> Get(ODataQueryOptions queryOptions)
    {
        return Ok(SetQueryOptions(_ModuleViewRepository.GetModuleViewData(userSession.OperatorActivities), queryOptions));
    }

    private IQueryable<T> SetQueryOptions<T>(IQueryable<T> data, ODataQueryOptions queryOptions) where T : class
    {
        return (IQueryable<T>)queryOptions.ApplyTo(data, new ODataQuerySettings { PageSize = 10 });
    }

但我有一個錯誤:

Cannot create an EDM model as the action 'Get' on controller 'Module' has a return type 'System.Threading.Tasks.Task`1[[Microsoft.AspNetCore.Mvc.ActionResult`1[[System.Linq.IQueryable`1[[DataBase.Models.DBObject.View.ModuleView, DataBase, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], System.Linq.Expressions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]], Microsoft.AspNetCore.Mvc.Core, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60]]' that does not implement IEnumerable<T>.

使用IHttpActionResult作為回報,您可以使用Ok()並且在此方法中您可以傳遞 JSON 數據此方法來自 IHttpActionResult 類

像這樣的東西:

  public IHttpActionResult GetStudent()
        {
            var StudentDtos = _context.Students.ToList();
            return Ok(StudentDtos);
        }

有很多返回方法可以用於IHttpActionResult類,也可以在這些 API 方法之上應用 HTTPS 方法

像這樣

[HttpDelete]
        public IHttpActionResult DeleteStudent(int id)
        {
            var student = _context.Students.FirstOrDefault(m => m.Id == id);
            if (student == null)
                return NotFound();

            _context.Students.Remove(student);
            _context.SaveChanges();
            return Ok();
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM