【发布时间】:2018-10-21 17:30:00
【问题描述】:
StackOverflow 美好的一天!我提出了一个新问题,因为我是 Web 服务的初学者,目前与我的问题类似的主题对我来说没有任何意义。非常欢迎我学习新东西。我很高兴收到来自社区的响应和支持。
目前我正在一家公司接受 Web 开发培训,我们的任务之一是使用 MVC 并为我们的 Aurelia 应用程序启用 CORS,使用“Microsoft ASP.NET Core 2.0 Web API”创建一个 Web 服务。
我的 Aurelia 应用托管在 http://localhost:9000/ 中,网络服务在 http://localhost:5000/ 中作为测试。
以下是我遇到的问题和我的观察:
每当我运行我的 Aurelia 应用程序时,我都会在浏览器控制台上收到此错误:"Failed to 加载http://localhost:5000/api/sample:对预检请求的响应 没有通过访问控制检查:没有“Access-Control-Allow-Origin” 请求的资源上存在标头。起源 'http://localhost:9000' 因此不允许访问。” 我的 C# 代码上是否有任何配置需要添加以便 这个错误要消失吗?
我使用 PostMan 来检查 Web 服务是否正常工作,是的确实工作。所以我想知道如果我访问有什么问题 我的 Aurelia 应用程序中的 Web 服务,它会生成一个错误。一世 猜猜错误在客户端?这里是截图 PostMan 请求和响应。
如果我将 aurelia 应用程序中的对象作为 HTTP POST 请求传递给 Web 服务,Web 服务是否会立即理解/映射 收到的对象值?
- 在 Web API 调试控制台上也显示:“CORS 策略中不允许请求方法 POST。”
为了简单起见,我在我的 Aurelia app.ts 上有这段代码,它是用 TypeScript 编写的,它通过 HTTP Post 动词请求示例数据:
import { inject } from 'aurelia-framework';
import { HttpClient } from 'aurelia-http-client';
@inject(HttpClient)
export class WebAPITest {
private httpClient: HttpClient;
private static readonly BASE_URL = `http://localhost:5000/api/`;
private message = `Web API Access Test! Pls. check the console.`;
constructor(httpClient: HttpClient) {
this.httpClient = httpClient;
this.httpClient.configure(requestBuilder => {
requestBuilder.withBaseUrl(WebAPITest.BASE_URL);
requestBuilder.withHeader('Content-Type', 'application/json'); // (?) Need clarifications.
});
}
activate() {
let sampleData = new SampleData();
return this.httpClient.post(`sample`, sampleData)
.then(response => {
if (response.isSuccess) {
this.data = response.content;
console.log(`SampleData Web Service Call SUCCEED!`);
} else {
console.log(`SampleData Web Service Call FAILED!`);
}
});
}
}
export class SampleData {
public name: string;
public age: number;
constructor() {
this.name = "Garfield";
this.age = 5;
}
}
这是我的 ASP.NET Core 2.0 MVC Web API 的代码:(Startup.cs)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
namespace Syslog.Web.GradeSheet.Backend
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
// For now it only accepts requests from localhost port 9000 which is the seat of our Aurelia applications.
app.UseCors(corsPolicyBuilder => {
corsPolicyBuilder.WithOrigins("http://localhost:9000");
});
app.UseMvc();
// Normally this will be fired up when no route has been matched.
app.Run(async (context) =>
{
await context.Response.WriteAsync("Welcome To GradeSheet Web Service! MVC has not found any Route that has been matched yet.");
});
}
}
}
这是我的 ASP.NET Core 2.0 MVC Web API 的代码:(SampleController.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace Syslog.Web.GradeSheet.Backend.Controllers
{
[Route("api/[controller]")]
public class SampleController : ControllerBase
{
[HttpPost]
public IActionResult getSampleObject([FromBody] SampleData sampleData) {
if(ModelState.IsValid) {
System.Diagnostics.Debug.WriteLine($"PRINTED: {sampleData.name} is {sampleData.age} years old.");
} else {
System.Diagnostics.Debug.WriteLine("ModelState is not Valid.");
}
return Ok($"Ok, got it, {sampleData.name}! You are {sampleData.age} years old.");
}
}
public class SampleData {
public string name { get; set; }
public int age { get; set; }
}
}
非常感谢您花时间阅读我的问题。我将不胜感激 解决方案、建议、附加信息或对我的代码的批评。祝你有美好的一天。
【问题讨论】:
-
我不知道为什么你的 MVC 不工作,但 Postman 工作,因为它不做浏览器会做的 cors 验证。使用浏览器开发工具查看请求/响应网络跟踪。
-
错误不是客户端,您可以尝试将以下内容添加到您的 CORS 构建器:
.WithOrigins(...).AllowAnyHeader().AllowAnyMethod().AllowCredentials()? -
@JessedeBruijne 没错!我添加了这段代码,它现在工作正常。呵呵谢谢! app.UseCors(corsPolicyBuilder => { corsPolicyBuilder.WithOrigins("localhost:9000", "localhost:9001"); corsPolicyBuilder.WithHeaders("content-type"); corsPolicyBuilder.WithMethods("GET", "POST", "PUT" ); });
标签: c# asp.net-core-mvc aurelia asp.net-core-2.0 asp.net-core-webapi