2015-06-30 45 views
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()); 

回答

1

檢查您的WebApiConfig類。 API的默認腳手架路徑通常是這樣的。

config.Routes.MapHttpRoute(
    name: "DefaultApi", 
    routeTemplate: "api/{controller}/{id}", 
    defaults: new { id = RouteParameter.Optional } 
); 

在你的情況下,你的url可能是這樣的。但是,這取決於您註冊了什麼routeTemplate。

client.UploadValues("http://localhost:1401/api/Registration/","POST", values); 

另外,我會建議不要調用你的方法或行爲Get()或Post(),這些名稱很容易與httpGet和httpPost混淆。

如果您認爲表單身份驗證阻止您發佈到網址,請註冊註冊控制器中的[授權]標籤,並嘗試重新發布。如果它仍然無法正常工作,那麼可能是您的網址,而不是身份驗證。

+0

我添加了我的文件WebApiConfig的代碼。 – Wido