c# - 如何在 .NET Core 中将数据作为 Json 响应写入 HttpResponse

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

我的代码如下所示:

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)。

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

最佳答案

您可以使用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 :

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.

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

如果你想将数据传递给 Controller ​​,你可以这样做:

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

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

关于c# - 如何在 .NET Core 中将数据作为 Json 响应写入 HttpResponse,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59280670/

相关文章:

c# - 拖放文件上传asp.net或java

c# - 从 Dotnet Google API 获取用户电子邮件信息

c# - 如何将具有固定模式的值数组反序列化为强类型数据类?

c# - 在 ASP.NET Core 2.0 中将 DataTable 转换为 IEnumerable<T>

c# - 有什么方法可以将 PDF 字节数组的一部分转换为单独的 PDF 文件吗?

c# - ExpandoObject 的真正优势是什么?

c# - 根据创建日期获取文件列表

c# - 使用 iTextSharp 生成 PDF

javascript - 插入登录函数 ASP.NET

c# - 如何根据c#中的列标题清除数据集行