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 项目中使用的名称相同。

posted @ 2021-12-22 17:55  sunshine静  阅读(55)  评论(0编辑  收藏  举报