从Asp.net web api 2过滤器属性响应返回JSON的正确方法

时间:2016-01-19 16:11:47

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

我正在使用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");

2 个答案:

答案 0 :(得分:3)

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

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

e.g:

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

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

答案 1 :(得分:0)

或许这样的事情,

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