SAREKA AVINASH
SAREKA AVINASH

Reputation: 479

How to Write data as Json Response to HttpResponse in .NET Core

My Code looks like :

public override void OnActionExecuting(ActionExecutingContext actionContext)
{
    object[] eventGridMessages = (object[])actionContext.ActionArguments.FirstOrDefault().Value;

    if (eventGridMessages == null || (eventGridMessages != null && eventGridMessages.Length <= 0))
    {
        throw new ArgumentNullException("eventGridMessages", "eventGridMessages parameter cannot be empty.");
    }

    if (actionContext.HttpContext.Request.Headers.ContainsKey("aeg-event-type") && actionContext.HttpContext.Request?.Headers["aeg-event-type"].ToString() == "SubscriptionValidation")
    {
        actionContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK;
        var x = this.GetValidationCodeResponse(eventGridMessages[0].ToString());
        actionContext.HttpContext.Response.ContentType = "application/json";
        actionContext.HttpContext.Response.Body = new MemoryStream(Encoding.UTF8.GetBytes(x, 0 , x.Length));
    }

    return;
}

/// <summary>
/// Gets the validation code response.
/// </summary>
/// <param name="validationRequest">The validation request.</param>
/// <returns>Validation Response Message</returns>
private string GetValidationCodeResponse(string validationRequest)
{
    var validationRequestJson = JsonConvert.DeserializeObject<CustomEvent<EventSubscritionValidationCode>>(Convert.ToString(validationRequest));
    var validationResponse = JsonConvert.SerializeObject(new { validationResponse = "644e4387-465f-46ee-8df9-b5330c3bda69" });

    return validationResponse;
}

Note : I'm performing AzureEventGrid operations. For authentication purposes, I'm implementing this filter which contains handshake code. Previously In the framework, we have a response of type HttpResponseMessage where we can set data as

actionContext.Response = new HttpResponseMessage   
{
    StatusCode = HttpStatusCode.OK,
    Content = new StringContent("JSON data")
}

but in .NET Core, it was changed to HttpResponse and it is an abstract class where I cannot create an instance and I'm unable to set JSON response to HttpResponse.

I'm unable to see my JSON data(GUID) on HttpResponse.

Could someone help me with this??

Upvotes: 3

Views: 5819

Answers (1)

Athanasios Kataras
Athanasios Kataras

Reputation: 26342

You can use the JsonResult. The way to short circuit a Result from WebApi is to set the context.Result value, so in your case

 if (actionContext.HttpContext.Request.Headers.ContainsKey("aeg-event-type") && actionContext.HttpContext.Request?.Headers["aeg-event-type"].ToString() == "SubscriptionValidation")
 {
     // JsonResult handles the serialization for you.
     actionContext.Result = new JsonResult(new { validationResponse = "644e4387-465f-46ee-8df9-b5330c3bda69" });
 }

As per documentation on the action context here:

Result

Gets or sets the IActionResult to execute. Setting Result to a non-null value inside an action filter will short-circuit the action and any remaining action filters.

There are multiple other types of IActionResult like BadRequestResult (400), NotFoundResult (404), and OkObjectResult (200) and more.

If you want to pass data to the contoller you can do this:

filterContext.HttpContext.Items["validationResponse"] = validationResponse;

Then you can get the extra fields and append them in your controller to the response, in an after execution filter, where your response won't override the one set in the filter.

Upvotes: 0

Related Questions