gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:52:20 28 4
gpt4 key购买 nike

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

最佳答案

也许是这样的,

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

关于c# - 从 Asp.net web api 2 过滤器属性响应返回 JSON 的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34881608/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com