Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Override 415 response in ASP.Net Core2.2

in .net core 2.2 ,has a default json with statuscode 415 like

{
   "type":"https://tools.ietf.org/html/rfc7231#section-6.5.13",
   "title":"Unsupported Media Type",
   "status":415,
   "traceId":"8000003e-0001-f500-b63f-84710c7967bb"
}

I don't know how this JSON came from. I follow the example below to rewrite json

But I got a different result,It added a section to the original json . This is my Wireshark Result

HTTP/1.1 415 Unsupported Media Type Transfer-Encoding: chunked

Content-Type: application/problem+json; charset=utf-8 Server:

Microsoft-IIS/10.0 X-Powered-By: ASP.NET Date: Mon, 06 May 2019 09:03:56 GMT

{
   "type":"https://tools.ietf.org/html/rfc7231#section-6.5.13",
   "title":"Unsupported Media Type",
   "status":415,
   "traceId":"8000002c-0002-fb00-b63f-84710c7967bb"
}
{
   "data":"this is custom message"
}

Filter:

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);
        }
    }
}
like image 488
Z.Chen Avatar asked May 06 '19 09:05

Z.Chen


1 Answers

I don't know how this JSON came from.

When the [ApiController] attribute is applied to a controller, it enables Problem details for error status codes, which ends up with a built-in action filter being added to the MVC filter pipeline for that controller. This action filter applies to all status-codes >= 400 and produces the JSON response you've described.

It added a section to the original json

When your MediaTypeResouceFilter.OnResourceExecuted code runs, the action filter I've noted above has already written JSON to the body. You write an additional JSON formatted string to the body, which just gets appended and mangles the response to be invalid JSON.

If you want to disable this problem details JSON from ever being written for responses, you can add the following to your Startup.ConfigureServices code to suppress the functionality:

services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressMapClientErrors = true;
    };
like image 96
Kirk Larkin Avatar answered Nov 09 '22 10:11

Kirk Larkin