Reputation: 19163
I am working with ASP.NET Web Api 2. I have created a action filter which checks for incoming request and then return a response back based on certain condition.
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");
}
}
I want to know is this the right way to return JSON response? I want to return a custom object (
var rebBody = new {message = "Unauthorized", payload = "", response = "401"};
) as JSON in the response body.
Does it make sense to use something like this:
var v = new {message = "Unauthorized", payload = "", response = "401"};
actionContext.Response.Content = new ObjectContent<object>(v, new JsonMediaTypeFormatter(), "application/json");
Upvotes: 3
Views: 7282
Reputation: 3122
You can use another overload of CreateResponse
:
public static HttpResponseMessage CreateResponse<T>(
this HttpRequestMessage request,
T value)
e.g:
var content = new { Property = 1 };
request.CreateResponse(content);
Upvotes: 3
Reputation: 2824
Something like this perhaps,
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;
}
}
or like this:
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;
}
}
Upvotes: 5