MVC 6 HttpResponseException

I am trying to return status codes as follows

throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "invalid username/password" });

now this is not supported in MVC6, which sucks because using IActionResult seems really silly and less intuitive to me. I found the following posts one and two . the first leads to a broken link, and the second refers to the MVC application.

I realized that I need to create middleware to solve this problem, but I'm not sure where to start, and since this is pretty useful stuff, I would expect that there will be some kind of open source solution that I could use, or maybe a piece of code.

For the record, I use the ASP.net 5 rc1 1 MVC 6 update

+4
source share
1 answer

I think this change is related to .NET Core - where ASP.NET is trying to do everything out of the box, ASP.NET Core only does what you specifically tell (which is a big part of why it is so much faster and more portable) .

If you want this behavior in Core you need to add, either as a package that someone wrote for you, or by its own.

It is pretty simple. First you need a special exception to check:

public class StatusCodeException : Exception
{
    public StatusCodeException(HttpStatusCode statusCode)
    {
        StatusCode = statusCode;
    }

    public HttpStatusCode StatusCode { get; set; }
}

Then you need a handler RequestDelegatethat checks for the new exception and converts it into the HTTP response status code:

public class StatusCodeExceptionHandler
{
    private readonly RequestDelegate request;

    public StatusCodeExceptionHandler(RequestDelegate next)
    {
        this.request = next;
    }

    public Task Invoke(HttpContext context) => this.InvokeAsync(context); // Stops VS from nagging about async method without ...Async suffix.

    async Task InvokeAsync(HttpContext context)
    {
        try
        {
            await this.request(context);
        }
        catch (StatusCodeException exception)
        {
            context.Response.StatusCode = (int)exception.StatusCode;
            context.Response.Headers.Clear();
        }
    }
}

:

public class Startup
{
    ...

    public void Configure(IApplicationBuilder app)
    {
        ...
        app.UseMiddleware<StatusCodeExceptionHandler>();

, HTTP , , unit test:

public Thing Get(int id) {
    Thing thing = GetThingFromDB();

    if (thing == null)
        throw new StatusCodeException(HttpStatusCode.NotFound);

    return thing;
}

, - , , , , .

+4

Source: https://habr.com/ru/post/1629781/


All Articles