【发布时间】: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