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.
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;
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With