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

Sha*_*der 3 .net c# 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");
            }
        }
Run Code Online (Sandbox Code Playgroud)

我想知道这是返回 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");
Run Code Online (Sandbox Code Playgroud)

jva*_*hyn 5

大概是这样的,

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

或者像这样:

       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;
        }
    }
Run Code Online (Sandbox Code Playgroud)