IHttpActionResult -明确指定OK()的状态

本文关键字:状态 OK IHttpActionResult | 更新日期: 2023-09-27 18:06:57

我有你的典型API路由,但是我需要它仍然返回与它正在使用的Ok JSON blob,但是我需要指定HttpStatusCode作为不同的东西。

这是API方法。

    [Route("detailedvarinfo/{VarGUID}")]
    public async Task<IHttpActionResult> GetDetailedVarInfo(string VarGUID)
    {
        if (!User.IsInRole("Admin"))
        {
            var DashboardAccess = (from DR in AuthDb.DashboardAccessVars
                                   where DR.ApplicationUser.Id == userInfo.Id
                                   select DR).
                                   AsEnumerable()
                                   .Select(x => new
                                   {
                                       VarGUID = x.VarGUID
                                   }).ToList();
            var FilteredVarInfo = VarInfo.Join(DashboardAccess, x => x.VarGUID, y => y.VarGUID, (x, y) => x);
            if (FilteredVarInfo.Any())
            {
                return Ok(FilteredVarInfo.FirstOrDefault());
            }
            else
            {
                return Ok(HttpStatusCode.Forbidden);
            }
        }
   }

我考虑过实现这一点,但没有任何运气。对于非ok响应,使用IHttpActionResult返回内容

也试过这样做…但没有任何运气。

     public class NotAllowedOkResult<T> : OkNegotiatedContentResult<T>
{
    public NotAllowedOkResult(T content, ApiController controller, HttpStatusCode statusCode)
        : base(content, controller)
    {
    }
    public NotAllowedOkResult(T content, IContentNegotiator contentNegotiator, HttpRequestMessage request,
        IEnumerable<MediaTypeFormatter> formatters, HttpStatusCode statusCode)
        : base(content, contentNegotiator, request, formatters)
    {
    }

    public override async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage response = await     base.ExecuteAsync(cancellationToken);
        return response;
    }        
}

IHttpActionResult -明确指定OK()的状态

成功了!真的很接近了,需要再做一点工作。

API方法

[Route("detailedvarinfo/{VarGUID}")]
public async Task<IHttpActionResult> GetDetailedVarInfo(string VarGUID)
{
    if (!User.IsInRole("Admin"))
    {
        var DashboardAccess = (from DR in AuthDb.DashboardAccessVars
                               where DR.ApplicationUser.Id == userInfo.Id
                               select DR).
                               AsEnumerable()
                               .Select(x => new
                               {
                                   VarGUID = x.VarGUID
                               }).ToList();
        var FilteredVarInfo = VarInfo.Join(DashboardAccess, x => x.VarGUID, y => y.VarGUID, (x, y) => x);
        if (FilteredVarInfo.Any())
        {
            return Ok(FilteredVarInfo.FirstOrDefault());
        }
        else
        {
            return NotAllowedOk(FilteredVarInfo, StatusReason.StatusFiltered);
        }
    }
}

BaseApiController: ApiController

protected internal virtual NotAllowedOkResult<T> NotAllowedOk<T>(T content, StatusReason statusReason)
{
    return new NotAllowedOkResult<T>(content, this, statusReason);
}  

StatusReason枚举

public enum StatusReason
{
    StatusFiltered
}
<<p> NotAllowedOkResult类/strong>
public class NotAllowedOkResult<T> : OkNegotiatedContentResult<T>
{
    public NotAllowedOkResult(T content, ApiController controller, StatusReason statusReason)
        : base(content, controller)
    {
        statusReasonCode = statusReason;
    }
    public NotAllowedOkResult(T content, IContentNegotiator contentNegotiator, HttpRequestMessage request,
        IEnumerable<MediaTypeFormatter> formatters, StatusReason statusReason)
        : base(content, contentNegotiator, request, formatters)
    {
        statusReasonCode = statusReason;
    }
    protected StatusReason statusReasonCode { get; set; }

    public override async Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        HttpResponseMessage response = await base.ExecuteAsync(cancellationToken);
        response.ReasonPhrase = GetStatusText(statusReasonCode);
        return response;
    }
    private static String GetStatusText(StatusReason reasonCode)
    {
        var retVal = "Unknown";
        switch (reasonCode)
        {
            case StatusReason.StatusFiltered:
                retVal = "Filtered";
                break;
        }
        return retVal;
    }
}
Javascript结果

varService.getDetailedJobInfo($stateParams.varGUID).then(function(results) {
    $scope.varDetails = results.data;
    return results;
}, function (error) {
    //alert(error.data.message);
});
//
// Actual result comes back properly!
//
results = {
   content: datablob,
   status: 200,
   statusText: "Filtered",
   config: datablob
}

可以使用HttpResponseMessage自定义响应。

HttpResponseMessage msg=new HttpResponseMessage(HttpStatusCode.OK);
msg.ReasonPhrase="Filterd";
return msg;