3 回答
TA贡献1841条经验 获得超3个赞
使用以下代码启用 CORS。.NET Core 版本:2.1 和 Angular 版本:1.6.7
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options =>
{
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
options.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
});
services.AddCors();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider)
{
app.UseCors(options =>
{
options.AllowAnyMethod();
options.AllowAnyOrigin();
options.AllowAnyHeader();
});
app.UseMvc();
}
}
角代码:
$http.post("http://localhost:52008/Account/GetJWT", credentials,{
headers: new HttpHeaders({
"Content-Type": "application/json"
})).then(
function(response) {
console.log(response);
},
function() {
console.log("unable to login");
});
如果问题仍然存在,请告诉我。
TA贡献1796条经验 获得超4个赞
您可以在 startup.cs 中配置核心,如下所示,并将源添加到 ConfigurationServices,如下所示。
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificOrigin",
builder => builder.WithOrigins("http://example.com"));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,
ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// Shows UseCors with named policy.
app.UseCors("AllowSpecificOrigin");
app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});
}
将 CORS 策略添加到特定操作。
[HttpGet]
[EnableCors("AllowSpecificOrigin")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
TA贡献1783条经验 获得超4个赞
public void ConfigureServices(IServiceCollection services)
{
//add cors service
services.AddCors(options => options.AddPolicy("Cors",
builder => {
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
} ));
services.AddMvc(); //
//--------------------------------------
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("Cors");//------>let app use new service
app.UseMvc();
}
在您的控制器内部,确保您从身体上抓取物体
//发布请求
[HttpPost]
public Message Post([FromBody] Message message)
{
var msg = new Message { Owner = message.Owner, Text = message.Text };
db.Messages.AddAsync(msg);
db.SaveChangesAsync();
return message;
}
- 3 回答
- 0 关注
- 381 浏览
添加回答
举报