我正在使用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");
答案 0 :(得分:3)
您可以使用CreateResponse
的另一个重载:
public static HttpResponseMessage CreateResponse<T>(
this HttpRequestMessage request,
T value)
e.g:
var content = new { Property = 1 };
request.CreateResponse(content);
答案 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;
}
}