【问题标题】:Right way to return JSON from Asp.net web api 2 filter attribute response从 Asp.net web api 2 过滤器属性响应返回 JSON 的正确方法
【发布时间】:2016-01-19 16:11:47
【问题描述】:

我正在使用 ASP.NET Web Api 2。我创建了一个操作过滤器,用于检查传入请求,然后根据特定条件返回响应。

public override void OnAuthorization(HttpActionContext actionContext)
        {
            var req = actionContext.Request;
            if (!req.Headers.Contains("x-key") || req.Headers.GetValues("x-key") == null)
            {
                actionContext.Response = req.CreateResponse(HttpStatusCode.Unauthorized);
                actionContext.Response.Content = new StringContent("Token required", Encoding.UTF8, "text/html");
            }
        }

我想知道这是返回 JSON 响应的正确方法?我想返回一个自定义对象( var rebBody = new {message = "Unauthorized", payload = "", response = "401"};) 作为响应正文中的 JSON。

这样使用有意义吗:

 var v = new {message = "Unauthorized", payload = "", response = "401"};
                actionContext.Response.Content = new ObjectContent<object>(v, new JsonMediaTypeFormatter(), "application/json");

【问题讨论】:

  • 您可能需要考虑返回一个 HttpResponseException

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


【解决方案1】:

可能是这样的,

    public override void OnAuthorization(HttpActionContext actionContext)
    {
        var req = actionContext.Request;
        if (!req.Headers.Contains("x-key") || req.Headers.GetValues("x-key") == null)
        {
            HttpResponseMessage responseMessage = new HttpResponseMessage()
            {
                Content = new StringContent("{\"message\":\"Unauthorized\", \"payload\":\"\",\"response\":\"401\"}")
            };
            responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            actionContext.Response = responseMessage;
        }
    }

或者像这样:

       public override void OnAuthorization(HttpActionContext actionContext)
    {
        var req = actionContext.Request;
        if (!req.Headers.Contains("x-key") || req.Headers.GetValues("x-key") == null)
        {
            var v = new { message = "Unauthorized", payload = "", response = "401" };
            HttpResponseMessage responseMessage = new HttpResponseMessage()
            {
                StatusCode = HttpStatusCodes.Unauthorized,
                Content = new StringContent(JsonConvert.SerializeObject(v))
            };
            responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            actionContext.Response = responseMessage;
        }
    }

【讨论】:

  • 这对我很有帮助,当我尝试在我的 web api 的 HandleUnauthorizedRequest 覆盖中创建自定义错误消息时
【解决方案2】:

您可以使用CreateResponse 的另一个重载:

public static HttpResponseMessage CreateResponse<T>(
    this HttpRequestMessage request,
    T value)

例如:

var content = new { Property = 1 };
request.CreateResponse(content);

见:https://msdn.microsoft.com/en-us/library/system.net.http.httprequestmessageextensions.createresponse(v=vs.118).aspx

【讨论】:

    猜你喜欢
    • 2015-09-21
    • 2021-05-17
    • 2018-07-02
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2019-03-16
    相关资源
    最近更新 更多