将cookie从控制器分配给外部html文件

时间:2016-11-21 05:39:41

标签: c# cookies asp.net-core asp.net-core-mvc .net-core

我正在使用.NET CORE 1.1.0能够从middleware分配和读取Cookie:

app.Run(async context =>
{
    context.Response.Cookies.Append("se_id","5");
    Console.WriteLine(context.Request.Cookies["se_id"]);

    await _next.Invoke(context);  
});

但是当我尝试从Controller做同样的事情时,我没有做任何事情,那么cookie既不会被写入也不会被阅读。

我在控制器中尝试使用下面的内容,但是没有用:

namespace ApiCall.Controllers
{
    [Route("api/[controller]")]
    public class FetchController : Controller
    {
        [HttpPost]
        public JsonResult Post([FromBody]object loginParam)
        {
            Response.Cookies.Append("id2","8");
            Console.WriteLine(Request.Cookies["se_id"]);

        }
    }
}

middleware处理Cookie并在controller

中处理Cookie之间有什么区别?

更新

我根据评论中给出的反馈更新了我的代码,我注意到以下内容: 1.控制器正在写入来自服务器的请求。 2.控制器未写入来自External文件

的请求

我更新的代码是:

controller.cs

using System;    // for Console.WriteLine
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;  // for Controller, [Route], [HttpPost], [FromBody], JsonResult and Json

namespace server
{
    [Route("api/[controller]")]
    public class ResinsController : Controller{

        [HttpGet]
        public JsonResult Get(){
           #region
              var result = new List<Item>();
              result.Add(new Item{Code = "320"});
           #endregion
         Response.Cookies.Append("id2", "8");
         Console.WriteLine(Request.Cookies["id2"]);
         return Json(result);
        }
    }

    public class Item{
        public string Code { get; set; }
   }
}

上面的代码工作正常,一旦我从http://localhost:60000/api/Resins

调用它

但是当我从外部文件调用它时不工作,外部文件是fetch的工作文件,因为我收到了返回的值,并且可以在concole中看到它,什么不起作用是处理cookies,我的index.html是:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <h2>
        Test page for using ajax call in webapi core.
    </h2>
    <button onclick="useFetch()">Use Fetch</button>

    <script type="text/javascript">
        function useFetch() {
            fetch('http://localhost:60000/api/Resins', {
                method: 'get'
            }).then(function(response) {
                return response.json();
            }).then(function(returnedValue) {
                var value = returnedValue;
                console.log(value);
            }).catch(function (err) {
                console.log(JSON.stringify(err));
            });
        }
    </script>
</body>                                           
</html>

如果需要,program.cs文件为:

using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Hosting;  // for WebHostBuilder()

namespace server{
    public class Program{
        public static void Main(string[] args){
            Console.WriteLine("Hello World!");
            #region Define Host
            var host = new WebHostBuilder()
                .UseKestrel()
                .UseUrls("http://localhost:60000", "https://localhost:60001")
                .UseStartup<Startup>()   // Startup is the class name, not the file name
                .Build();
            #endregion

        host.Run();
        }
    }
}

startup.cs文件是:

using Microsoft.Extensions.DependencyInjection;  // for IServiceCollection
using Microsoft.AspNetCore.Builder;   // for IApplicationBuilder and FileServerOptions
using Microsoft.AspNetCore.Hosting;  // for IHostingEnvironment

namespace server{
    public class Startup{
        public void ConfigureServices(IServiceCollection services){
            services.AddCors();  // to be accesssed from external sites, i.e. outside the server
            services.AddMvc();   // to use Controllers, Add framework services.
        }
        public void Configure(IApplicationBuilder app, IHostingEnvironment env){
            app.UseCors(builder =>   // to be accesssed from external sites, i.e. outside the server
                        builder.AllowAnyOrigin()
                               .AllowAnyHeader()
                               .AllowAnyMethod()
                               .AllowCredentials()
                        );
            app.UseMvc();          
        }
    }
}

project.json文件是:

{
  "version": "1.0.0-*",
  "buildOptions": {
    "debugType": "portable",
    "emitEntryPoint": true
  },
  "dependencies": {
    "Microsoft.AspNetCore.Server.Kestrel": "1.1.0",
    "Microsoft.AspNetCore.Mvc": "1.1.0"
  },
  "frameworks": {
    "netcoreapp1.1": {
      "dependencies": {
        "Microsoft.NETCore.App": {
          "type": "platform",
          "version": "1.1.0"
        }
      },
      "imports": "dnxcore50"
    }
  }
}

更新2

在检查browser developer tool中的不同屏幕时,我发现了附件: 1. Application屏幕清楚地提到没有饼干, 2. Network - &gt; Cookies屏幕显示cookie已正确写入,但控制器无法将其读回,这意味着控制器尝试从Application cookies读取cookie而不是Network cookies

enter image description here

1 个答案:

答案 0 :(得分:0)

我找到了这个post的指南,其中的问题看起来与外部html文件中的请求有关,而不是与控制器编程相关,如上所述here

  来自其他域的

XmlHttpRequest响应无法为自己的域设置cookie值,除非在发出请求之前将forCredentials设置为true,而不管Access-Control-header值

在我的代码中,将id添加到fetch后工作正常,因此原始代码变为:

#yourDivId input[type="radio"] {
    ... your declarations here ...
}

现在可以从控制器中读取Cookie,但在浏览器开发人员工具中,仍然可以在credentials: 'include'下看到,fetch('http://localhost:60000/api/Resins', { credentials: 'include', method: 'get' }).then(function(response) { return response.json(); }).then(function(returnedValue) { var asdf = returnedValue; console.log(asdf); }).catch(function (err) { console.log(JSON.stringify(err)); }); 下没有任何内容。

enter image description here