In a recent blog entry, we explained how to call an MVC Controller method from ASPX code-behind code. The demo didn't use any authorization and therefore, all methods were accessible anonymously.

When an authorization method is used, the HttpWebRequest won't be authorized and will be routed to the specified MVC login page. As most applications are using an authorization method, there are two ways of solving this:

  1. Usage of the AllowAnonymousAttribute

    This attribute marks controllers and actions to skip the authorization. With this attribute, the Controller method would look like this:

    public bool SaveTemplate(string document)
    // these are the values coming from the HTTP Post action
    // of the ASPX page
    string doc = document;
    // the document can now be saved in your Controller action
    // ...
    // return true, if successful
    return true;
    view raw Controller.cs hosted with ❤ by GitHub
  2. Sending the AuthCookie with the request

    In this case, the authorization cookie will be sent with the WebRequest to authorize the request. The following code shows how to request the AuthCookie in order to add a newly created cookie to the HttpWebRequest:

    Uri uri = new Uri("http://" +
    Request.Url.Authority + "/Home/SaveTemplate");
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    // get the AuthCookie
    var authCookie =
    FormsAuthentication.GetAuthCookie(User.Identity.Name, true);
    // create a new Cookie
    Cookie requestAuthCoockie = new Cookie()
    Expires = authCookie.Expires,
    Name = authCookie.Name,
    Path = authCookie.Path,
    Secure = authCookie.Secure,
    Value = authCookie.Value,
    Domain = uri.Host,
    HttpOnly = authCookie.HttpOnly,
    // add the AuthCookie to the WebRequest
    request.CookieContainer = new CookieContainer();
    view raw Editor.aspx.cs hosted with ❤ by GitHub

    It is important to mention that FormsAuthentication must be enabled in this scenario:

    <authentication mode="Forms"/>
    view raw web.config.xml hosted with ❤ by GitHub