如何在angular中正确使用ISession和会话Cookie-asp.net.core应用

时间:2019-04-16 08:45:48

标签: c# html angular asp.net-core cookies

我在使用Angular 7中的前端和ASP.NET.Core 2.1中的后端创建Web应用程序中处于中间位置。在服务器端,我想实现一个简单的会话功能。因此,在Startup.cs中,我使用AddDistributedMemoryCache()AddSession()UseSession()配置会话。在服务器域中,一切正常。我有会话cookie,可以从控制器,存储库等访问会话。 问题是当我从另一个域(从Angular的前面)调用html方法时。在HtmlRequest中,没有有关cookie会话的信息,因此HttpContext.Session.Id总是不同的。我可以将My.Cookie的值发送到前端以通过ngx-cookie-service在前端创建cookie吗?然后,此Cookie将自动发送到HtmlRequest中的后端。我如何从后端访问此Cookie?我只能从请求中获取Cookie,而前端的请求没有My.Cookie。还是在前端和后端之间自动交换My.Cookie?

目前,我将自己的静态存储创建为单例服务,但我认为使用ISession应该是更好的解决方案。

Startup.cs

public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            services
                .AddCors(options =>
                {
                    options.AddPolicy("MyCorsPolicy", policyBuilder =>
                    {
                        policyBuilder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowCredentials()
                        .AllowAnyHeader();
                    });
                })
                .AddDistributedMemoryCache()
                .AddSession(options =>
                {
                    options.IdleTimeout = TimeSpan.FromHours(1);
                    options.Cookie = new CookieBuilder { Name = "My.Cookie", HttpOnly = false, IsEssential = true, SameSite = SameSiteMode.None };
                });
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app
                .UseCors("MyCorsPolicy")
                .UseSession()
                .UseMvc(routes =>
                {
                    routes.MapRoute("default",
                        "{controller}/{action}",
                        new { controller = "Home", action = "Index" });
                });
        }
    }

FooController.cs

    [Route("api/[controller]")]
    [ApiController]
    public class FooController : ControllerBase
    {
        [HttpGet]
        public IActionResult FooGet()
        {
            return new OkObjectResult(new { message = HttpContext.Session?.GetString("Message") ?? string.Empty, sessionId = HttpContext.Session.Id });
        }

        [HttpPost]
        public IActionResult FooPost(dynamic clientSite)
        {
            string message = clientSite["message"];
            HttpContext.Session.SetString("Message", message);
            return new OkObjectResult(true);
        }
    }

rest.server.ts

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class RestServer {
  private url = `http://${location.hostname}:60000\\api\\foo`;

  constructor(private http: HttpClient) { }

  public GetFoo(): Observable<any> {
    return this.http.get(this.url);
  }

  public PostFoo(message: string): Observable<any> {
    return this.http.post(this.url, {message});
  }
}

0 个答案:

没有答案