Webservice code
[Authorize]
public class RegistrationController : ApiController
{
[AllowAnonymous]
[HttpPost]
public string Get(string user,string pass)
{
if (user=="abc"&&pass=="cba")
FormsAuthentication.SetAuthCookie("HomeUser", false);
return "Home";
}
[HttpGet]
public string Post()
{
return "Post";
}
}
Forms Authentication from console
class CookieWebClient : WebClient
{
public CookieContainer CookieContainer { get; private set; }
/// <summary>
/// This will instanciate an internal CookieContainer.
/// </summary>
public CookieWebClient()
{
this.CookieContainer = new CookieContainer();
}
/// <summary>
/// Use this if you want to control the CookieContainer outside this class.
/// </summary>
public CookieWebClient(CookieContainer cookieContainer)
{
this.CookieContainer = cookieContainer;
}
protected override WebRequest GetWebRequest(Uri address)
{
var request = base.GetWebRequest(address) as HttpWebRequest;
if (request == null) return base.GetWebRequest(address);
request.CookieContainer = CookieContainer;
return request;
}
}
The program's objective is to log into a Web service, and then query the secure authorization methods and then reset the authorization. How to do it the easiest way?
using (var client = new CookieWebClient())
{
var values = new NameValueCollection
{
{ "user", "abc" },
{ "pass", "cba" },
};
client.UploadValues("http://localhost:1401/Get/","POST", values);
// If the previous call succeeded we now have a valid authentication cookie
// so we could download the protected page
string result = client.DownloadString("http://localhost:1401");
}
I have an error 405 Unknown method on line UploadValues. Can you help me? I use the authorization by means of forms, as I find this method as simple as possible and at the same time safe.
P.S. WebApiConfig code:
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{api}/{id}",
defaults: new { controller="Registration",
api=RouteParameter.Optional,
id = RouteParameter.Optional }
);
config.Filters.Add(new AuthorizeAttribute());