此请求有效,但如果提交的请求抛出错误(系统中不存在电子邮件),我会收到CORS策略错误。
CORS策略已阻止从源“http://localhost:6420”访问位于“https://my-website.azurewebsites.net/Assign/ByEmail?客户端电子邮件= bademailaddress%40gmail.com和管理器电子邮件=some_mnger%40gmail.com”的XMLHttpRequest:请求的资源上不存在“Access-Control-Allow-Origin”标头。
这是一个Asp.Net Core Web API解决方案。它仅在部署到其Azure环境时才会表现出此行为,而在作为localhost运行时不会表现出此行为。
Program.cs
using Microsoft.Identity.Web;
using System.Configuration;
using Microsoft.Extensions.Configuration;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Cors.Infrastructure;
using wld.admin.api;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
var allowAnyOriginsPolicyName = "_allowAnyOriginsPolicy";
builder.Services.AddCors(corsOptions =>
{
corsOptions.AddPolicy(name: allowAnyOriginsPolicyName,
policyBuilder =>
{
policyBuilder
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// Adds Microsoft Identity platform (Azure AD B2C) support to protect this Api
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(options =>
{
builder.Configuration.Bind("AzureAdB2C", options);
options.TokenValidationParameters.NameClaimType = "name";
},
options => { builder.Configuration.Bind("AzureAdB2C", options); });
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseCors(allowAnyOriginsPolicyName);
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
var connectionString = builder.Configuration.GetConnectionString("xxxxx_api");
app.Run();
客户代码
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<button type="button" id="callAssign" onclick="apiGet('Assign/ByEmail', {clientEmail:'bademailaddress@gmail.com', managerEmail:'some_mnger@gmail.com@sendmailtest.com'})">Assign By Email</button>
JS系统
async function apiExec(type, endPoint, params, data)
{
var serverAndEndPoint = apiConfig.webApi + endPoint;
logMessageTime(serverAndEndPoint);
if(params != null)
logMessageTime('parameters: ' + JSON.stringify(params));
getTokenPopup(tokenRequest)
.then(response => {
if (response) {
try {
const headers = { headers: {"Authorization" : `Bearer ${response.accessToken}`} }
// axios.get(serverAndEndPoint,headers)
axios({
method: type,
url: serverAndEndPoint,
headers : {"Authorization" : `Bearer ${response.accessToken}`},
params : params,
data : data
})
.then(response2 => {
console.log(response2);
console.log(response2.data);
logMessageTime(JSON.stringify(response2.data));
return response2.data;
}, reject => {
console.log("reject");
console.log(reject);
})
.catch(error)
{
console.log("error caught in apiExec promise");
console.log(error);
}
//callApi(apiConfig.webApi + methodAndParameters, response.accessToken);
} catch (error)
{
console.log("error caught in apiExec");
console.log(error);
}
}
});
}
控制器代码
namespace my.api.Controllers
{
[Authorize]
[RequiredScope("tasks.read")]
[ApiController]
[Route("[controller]")]
public class AssignController : ControllerBase
{
private readonly ILogger<AssignController> _logger;
private string _connectionString = "";
private IConfiguration _configuration = null;
public AssignController(ILogger<AssignController> logger, IConfiguration configuration)
{
_logger = logger;
_connectionString = configuration.GetConnectionString("xxxxx_api");
_configuration = configuration;
}
[HttpGet]
[Route("ByEmail")]
public bool ByEmail(string clientEmail, string managerEmail)
{
new ManagerOps(_logger, _configuration).AssignToClientByEmail(clientEmail, managerEmail);
return true;
}
}
}
1条答案
按热度按时间chhqkbe11#
您需要有一些错误处理代码,即使这意味着有一个返回false的try,catch语句。我的假设是,当控制器遇到某种错误时,响应中没有包含正确的标头。