繁体   English   中英

如何配置后端C#服务器?

[英]How to configure back-end C# server?

我想问这个问题:如果我选择 C# (ASP.NET) 作为我的项目的后端语言,我需要如何配置它以启用 CORS 到特定域? 几天来我一直在努力解决这个问题并使用了我找到的所有东西,但最后使用[EnableCors]Response.Headers.Add()根本不起作用。 这是我的文件: Server.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Microsoft.AspNetCore.Cors;

namespace spider_web.Data;
[ApiController]
[EnableCors()]
//Base class for all back-end interactions. Contains the basic methods for CRUD operations.
public class Server: ControllerBase {
    //Logs user in with token-based authentication.
    public Server() {
        StringValues token = new StringValues("*");
        Response.Headers.Add("Access-Control-Allow-Origin", token);
    }
    [HttpPost("/login")]
    public void Login(string username, string position, string password) {
        // ...
    }
    //Test method for verifying port connection. List of chars is the arbitrary value.
    [HttpGet("/fetch")]
    public IActionResult Fetch() {
        // None of these worked.
        //Response.Headers.Add("Access-Control-Allow-Origin", "*");
        //HttpContext.Request.Headers["Access-Control-Allow-Origin"] = "http://localhost:4200";
        return Ok(new List<char> { 'a', 'b', 'c' });
    }
}

程序.cs

using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using spider_web.Data;



var builder = WebApplication.CreateBuilder(args);
//string[] origins = new string[3] { "http://localhost:4200", "http://localhost:7093", "http://localhost:5226" };


builder.Services.AddCors(options =>
{
    options.AddPolicy("Allow-local-host", builder =>
    {
        builder.AllowAnyOrigin()
            .AllowAnyHeader()
            .AllowAnyMethod();
                      });
});


// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();
builder.Services.AddMvc();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();

app.UseStaticFiles();

app.UseRouting();
app.UseCors();
app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

这是我称之为后端的 Angular 组件:

import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-chars',
  templateUrl: './chars.component.html',
  styleUrls: ['./chars.component.css']
})
export class CharsComponent implements OnInit {

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    let headers = new HttpHeaders();
    headers.append('Access-Control-Allow-Origin', '*');
    this.http.get("http://localhost:5226/fetch", {headers}).subscribe(
      response => {console.log(response)}, error => {console.log(error)});
  }
}

提前谢谢大家!

嘿,这就是我的做法:

services.AddCors(options => options.AddDefaultPolicy(builder => builder
            .AllowAnyHeader()
            .AllowAnyMethod()
            .WithOrigins("domain1.com", "domain2.com")
        ));

有关 CORS 的更多信息: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0#dp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM