MVC webapi Authentication

已经有了MVC做的项目了,项目中采用了form 认证,但是项目需要启动几个web api 供别人调用。如何给web api 加身份认证呢?

[Authorize]
public ActionResult CallWebApi()
{
    var baseAddress = new Uri("https://example.com");
    var cookieContainer = new CookieContainer();
    using (var handler = new HttpClientHandler() { CookieContainer = cookieContainer })
    using (var client = new HttpClient(handler) { BaseAddress = baseAddress })
    {
        var authCookie = Request.Cookies[FormsAuthentication.FormsCookieName].Value;
        cookieContainer.Add(baseAddress, new Cookie(FormsAuthentication.FormsCookieName, authCookie));
        var result = client.GetAsync("/api/values").Result;
        result.EnsureSuccessStatusCode();

        // now you can read the result.Content ...
    }
}

假设您还在 Web API 项目的 web.config 中启用了form身份验证,并且 cookie 名称与 MVC 项目中使用的名称相同。

每天进步一点~~~ 如果你觉得本文对你有帮助,请点击“推荐”,如果想第一时间了解我的更新,请点击公告栏里的“+关注”,谢谢关注我的好友~!
原文地址:https://www.cnblogs.com/sunShineJing/p/15720573.html