WebClient中的WebClient FormsAuthentication

时间:2015-06-30 15:45:21

标签: c# asp.net-web-api

网络服务代码

[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 个答案:

答案 0 :(得分:1)

检查WebApiConfig类。 api的默认scaffolded路径通常是这样的。

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

在你的情况下你的网址可能是这样的。但这取决于您注册的routeTemplate。

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

另外我建议不要调用你的方法或动作Get()或Post(),这些名字太容易与httpGet和httpPost混淆。

如果您认为表单身份验证阻止您发布到网址,请注册注册控制器中的[授权]标记并尝试再次发布。如果它仍然无法正常工作,则可能是您的网址,而不是身份验证。