1
Webservice的代碼WebClient的FormsAuthentication中的WebAPI從控制檯
[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";
}
}
窗體身份驗證
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;
}
}
該計劃的目標是登錄到Web服務,然後查詢安全的授權方法,然後重置權限。如何做到最簡單的方法?
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");
}
我有一個錯誤405行上的未知方法UploadValues。你可以幫我嗎?我通過表單的方式使用授權,因爲我發現這種方法儘可能簡單,同時也是安全的。
P.S. WebApiConfig代碼:
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());
我添加了我的文件WebApiConfig的代碼。 – Wido