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:
-
Usage of the AllowAnonymousAttribute
This attribute marks controllers and actions to skip the authorization. With this attribute, the Controller method would look like this:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters[HttpPost] [AllowAnonymous] 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; } -
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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersUri 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(); request.CookieContainer.Add(requestAuthCoockie); It is important to mention that FormsAuthentication must be enabled in this scenario:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters<system.web> <authentication mode="Forms"/> </system.web>