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

时间:2015-08-06 22:21:06

标签: c# asp.net-mvc asp.net-web-api asp.net-web-api2 httpresponse

我有你的典型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);
            }

        }
   }

我看着实施这个,但没有任何运气。 Return content with IHttpActionResult for non-OK response

还试图做这样的事情..但没有任何运气。

     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;
    }        
}

2 个答案:

答案 0 :(得分:1)

搞定了!非常接近,需要做更多的工作。

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 Enumeration

public enum StatusReason
{
    StatusFiltered
}

NotAllowedOkResult Class

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
}

答案 1 :(得分:0)

您可以使用 HttpResponseMessage 自定义响应。

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

return msg;