【问题标题】:How to Write data as Json Response to HttpResponse in .NET Core如何将数据作为 Json 响应写入 .NET Core 中的 HttpResponse
【发布时间】:2020-04-04 10:23:45
【问题描述】:

我的代码如下:

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

注意: 我正在执行AzureEventGrid 操作。出于身份验证的目的,我正在实现这个包含握手代码的过滤器。以前在框架中,我们有一个HttpResponseMessage类型的响应,我们可以将数据设置为

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

但在 .NET Core 中,它已更改为 HttpResponse,它是一个抽象类,我无法在其中创建实例,也无法将 JSON 响应设置为 HttpResponse

我无法在 HttpResponse 上看到我的 JSON 数据 (GUID)。

有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: c# asp.net .net azure azure-eventgrid


    【解决方案1】:

    您可以使用JsonResult。从 WebApi 短路 Result 的方法是设置 context.Result 值,所以在你的情况下

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

    根据文档on the action context here

    结果

    获取或设置要执行的 IActionResult。在动作过滤器中将 Result 设置为非空值将使动作和任何剩余的动作过滤器短路。

    IActionResult 还有多种其他类型,例如 BadRequestResult (400)、NotFoundResult (404) 和 OkObjectResult (200) 等等。

    如果您想将数据传递给控制器​​,您可以这样做:

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

    然后您可以获得额外的字段并将它们附加到控制器中的响应中,在执行后过滤器中,您的响应不会覆盖过滤器中的设置。

    【讨论】:

    • 我不能使用 actionContext.Result 因为如果我将它设置为结果它不会到达我的端点,执行只会在过滤器处停止。
    • 那么,为了理解它,您想编辑 JsonResponse 并添加一些额外的属性吗?
    猜你喜欢
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    • 2011-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-18
    • 1970-01-01
    相关资源
    最近更新 更多