Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Could not modify reason phrase on HttpResponse object in asp vNext

I have to set the reason phrase in my asp 5 middle-ware, not just the status code for the http response messages, but I could not found any way to do it. The StatusCode property of the Microsoft.AspNet.Http.HttpResponse class is an int property for modifying the status code only, but not the reason text.

I understand, that the reason is set automatically according to the status code, but in my case I have to set it to custom values. Which is OK according to the HTTP RFC 2616:

[..] The reason phrases listed here are only recommendations -- they MAY be replaced by local equivalents without affecting the protocol. [..]

I'm currently using beta-8 version of the asp 5 framework.

like image 860
Gergely Hamos Avatar asked Oct 19 '25 10:10

Gergely Hamos


2 Answers

You could try:

Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "some reason";

An HttpStatusCodeResult that also returns a reason could look like:

public class BadRequestResult : HttpStatusCodeResult
{
    private readonly string _reason;

    public BadRequestResult(string reason) : base(400)
    {
        _reason = reason;
    }

    public override void ExecuteResult(ActionContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException(nameof(context));
        }

        context.HttpContext.Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = _reason;
        context.HttpContext.Response.StatusCode = StatusCode;
    }
}
like image 93
Hannes Sachsenhofer Avatar answered Oct 22 '25 00:10

Hannes Sachsenhofer


Try this

public class HomeController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Title = "Home Page";

        return View();
    }

    public ActionResult TestError() // id = error code 
    {
        return new HttpStatusCodeResult(301, "Your custom error text");
    }
}

Now check http://localhost:33470/home/Testerror

And look at Fiddler enter image description here

like image 38
slava Avatar answered Oct 22 '25 00:10

slava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!