zoukankan      html  css  js  c++  java
  • 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 项目中使用的名称相同。

    每天进步一点~~~ 如果你觉得本文对你有帮助,请点击“推荐”,如果想第一时间了解我的更新,请点击公告栏里的“+关注”,谢谢关注我的好友~!
  • 相关阅读:
    HTTP协议图解
    .NET 发布网站步骤
    使用php在服务器端生成图文验证码
    SQLServer复习文档1(with C#)
    理解 JavaScript 原型 / 原型链
    浅谈瀑布流
    懒加载
    jQuery ajax
    jQuery 动画效果 与 动画队列
    jQuery 事件
  • 原文地址:https://www.cnblogs.com/sunShineJing/p/15720573.html
Copyright © 2011-2022 走看看