本文介绍了在ASP.Net Core中覆盖415响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.net Core 2.1中,我想返回一个Json响应以及状态代码415,而不是默认返回的只是415.

In ASP.net Core 2.1, I want to return a Json response along with Status code 415 instead of just 415 returned by default.

为此,我使用了资源过滤器:

To achieve this I am using a resource filter:

public class MediaTypeResouceFilter : Attribute, IResourceFilter
{
    public void OnResourceExecuting(ResourceExecutingContext context)
    {
    }

    public void OnResourceExecuted(ResourceExecutedContext context)
    {
        if (context.HttpContext.Response.StatusCode == 415)
        {
            context.Result = new ContentResult() { StatusCode = 415, Content = JsonConvert.SerializeObject(myResponse), ContentType = "application/json" };
        }
    }
}

在调试中,我看到了上下文.结果被成功覆盖,但邮递员只得到415,没有Json响应.

In debugging, I see that context.Result is being overrided successfully but postman gets only 415 with no Json response.

如果我放:

context.Result = new ContentResult() { StatusCode = 415, Content = JsonConvert.SerializeObject(myResponse), ContentType = "application/json" };

在OnResourceExecuting内而不是OnResourceExecuted内,它按我的意愿工作,但问题是我无法在执行资源之前检查状态代码.

inside OnResourceExecuting instead of OnResourceExecuted, it works as I wish but the thing is that I can't check for status code before executing resource.

为什么会这样?

推荐答案

您可以尝试吗?

public class MediaTypeResouceFilter : Attribute, IResourceFilter
    {
        public void OnResourceExecuting(ResourceExecutingContext context)
        {
        }

        public void OnResourceExecuted(ResourceExecutedContext context)
        {
            if (context.HttpContext.Response.StatusCode == 415)
            {
                var jsonString = JsonConvert.SerializeObject(new { data = "this is custom message" });
                byte[] data = Encoding.UTF8.GetBytes(jsonString);
                context.HttpContext.Response.Body.WriteAsync(data, 0, data.Length);
            }
        }
    }

然后您将获得415状态码,正文数据为: {"data":这是自定义消息"}

Then you can get a 415 Status Code and body data is: {"data":"this is custom message"}

实际上 OnResourceExecuted 触发得太晚了,但是您可以修改自定义消息的正文

Actually OnResourceExecuted fires too late but you can modify the body for your custom message

这篇关于在ASP.Net Core中覆盖415响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 04:56