WebClient表单WebAPI中的身份验证
本文关键字:身份验证 WebAPI 表单 WebClient | 更新日期: 2023-09-27 18:00:28
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";
}
}
从控制台进行表单验证
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");
}
UploadValues行上有一个错误405未知方法。你能帮我吗?我通过表格的方式使用授权,因为我发现这种方法尽可能简单,同时又安全。
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类。api的默认scaffolded路径通常如下所示。
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
在你的情况下,你的网址可能是这样的。但这将取决于您注册的路由模板。
client.UploadValues("http://localhost:1401/api/Registration/","POST", values);
此外,我建议不要调用您的方法或操作Get()或Post(),这些名称很容易与httpGet和httpPost混淆。
如果您认为表单身份验证阻止您发布到url,请从注册控制器中注释掉[授权]标记,然后尝试再次发布。如果它仍然不起作用,那可能是你的url,而不是身份验证。