rpmansion
rpmansion

Reputation: 2014

Url redirection on OnActionExecuting method

We are trying to implement a non-hosted header that will accept anything before *.website.com in ASP.NET. Since it will accept any subdomain, we extended the HttpContextBase class to add custom method.

public static bool ValidateHost(this HttpContextBase context)
{
    var domain = context.Request.Url.Host;

    //add logic to check if the host is valid and the subdomain exist in the database

    return false;
}

This method will validate whether the context.Url.Host is a valid host or its subdomain exist in the database if not then redirect the request to the default host website.com. To do that I added this line of codes below in our BaseController:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (!filterContext.HttpContext.ValidateUrl())
    {
        filterContext.HttpContext.Response.Redirect("https://website.com/");
        return;
    }
}

It redirects to default host whenever it returns false, however it throws an exception: {"Server cannot append header after HTTP headers have been sent."}

Am I missing something here or the logic is incomplete?

Upvotes: 4

Views: 731

Answers (2)

Rahul Nikate
Rahul Nikate

Reputation: 6337

In HTTP there is always single response for each request. So this error means that you've already send something to response and again you are requesting for other URL.

Upvotes: 1

Bon Macalindong
Bon Macalindong

Reputation: 1320

Try RedirectResult

filterContext.Result = new RedirectResult("https://website.com");

Upvotes: 3

Related Questions