简体   繁体   English

WebAPI中的WebClient FormsAuthentication

[英]WebClient FormsAuthentication in WebAPI

Webservice code Web服务代码

[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. 该程序的目标是登录Web服务,然后查询安全授权方法,然后重置授权。 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. 我在上传值行上出现错误405未知方法。 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. 我通过表格使用授权,因为我发现此方法尽可能简单,同时又很安全。

PS WebApiConfig code: PS 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());

Check you WebApiConfig class. 检查您的WebApiConfig类。 The default scaffolded path for api is usually something line this. api的默认脚手架路径通常在此行上。

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

In you case you url could be something like this. 在这种情况下,您的网址可能是这样的。 But that will depend on what routeTemplate you have registered. 但这取决于您注册了哪种routeTemplate。

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

Also I would recommend not calling your methods or actions Get() or Post(), those names are too easily confused with httpGet and httpPost. 我也建议不要调用您的方法或操作Get()或Post(),这些名称很容易与httpGet和httpPost混淆。

If you think the forms authentication is stopping you from posting to the url, comment out the [Authorize] tags from the Registration controller and try to post again. 如果您认为表单身份验证阻止您发布到url,请从“注册”控制器中注释掉[Authorize]标签,然后尝试再次发布。 If it still not working it is probably you url and not the authentication. 如果仍然无法正常工作,则可能是您输入的是网址,而不是身份验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#WebClient表单身份验证 - C# WebClient FormsAuthentication WebAPI不通过控制器维护FormsAuthentication - WebAPI doesn't maintain FormsAuthentication over controllers ASP.NET WebApi FormsAuthentication 401(未经授权)问题 - ASP.NET WebApi FormsAuthentication 401 (Unauthorized) issue 基于资源的ASP.NET授权FormsAuthentication和WebApi - Resource based ASP.NET Authorization FormsAuthentication and WebApi 如何使用WebClient通过[FromBody] POST到WebAPI - How to use WebClient to POST to WebAPI using [FromBody] 如何在WebApi中使用AuthorizationFilterAttribute和WebClient库? - How use AuthorizationFilterAttribute in WebApi with WebClient Library? 使用 WebClient 调用具有复杂对象参数的 WebApi - Calling WebApi with complex object parameter using WebClient 大型视频文件无法通过WebClient.UploadFileTaskAsync上传到WebApi - Large video files failing to upload to a WebApi via WebClient.UploadFileTaskAsync 如何读取通过WebClient.UploadString发送的WebAPI中的值? - How to read a value in WebAPI sent via WebClient.UploadString? 如何通过WebClient或HttpClient发布产品列表,以及如何为其使用WebAPI控制器? - How to POST list of Product by WebClient or HttpClient and how to whire WebAPI controller for it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM