- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
角度网络应用程序:
http://localhost:57729/
VS 2017, Core 2.1
应用程序接口(interface):
http://localhost:3554
VS 2017, .Net 4.6
我遇到了 cors 问题,一直在实现不同的解决方案,但到目前为止没有成功。在这种情况下不会发生身份验证。我有测试 API Controller ,它有一个返回 OK 响应的 get 方法。
直接执行测试 http://localhost:3554/MWAPI/Test
给我这个结果
当我尝试从 Angular 网络应用程序运行它时,我遇到了以下 cors 问题
跨源请求被阻止:同源策略不允许读取位于 http://localhost:3554/MWAPI/test 的远程资源。 (原因:CORS header “Access-Control-Allow-Origin”与“(null)”不匹配)。
我已经查看了多种资源,但它仍然不适合我。
https://www.codeproject.com/Articles/617892/Using-CORS-in-ASP-NET-WebAPI-Without-Being-a-Rocke
这是我现在拥有的...
网络配置:
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
//url is without the trailing slash
//var cors = new System.Web.Http.Cors.EnableCorsAttribute("http://localhost:57729", "*", "*");
var cors = new System.Web.Http.Cors.EnableCorsAttribute(origins: "http://localhost:57729", headers: "*", methods: "*");
config.EnableCors(cors);
var constraints = new { httpMethod = new HttpMethodConstraint(HttpMethod.Options) };
config.Routes.IgnoreRoute("OPTIONS", "*pathInfo", constraints);
//testing... or remove all formats
config.Formatters.XmlFormatter.SupportedMediaTypes.Clear();
//testing... and add indenting and camel case if we need
config.Formatters.JsonFormatter.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute("DefaultApiWithId", "MWAPI/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
config.Routes.MapHttpRoute("DefaultApiWithAction", "MWAPI/{controller}/{action}");
config.Routes.MapHttpRoute("DefaultApiGet", "MWAPI/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
config.Routes.MapHttpRoute("DefaultApiPost", "MWAPI/{controller}", new { action = "Post" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Post) });
}
使用以下内容检查 API,连接没有问题
我在这里遗漏了其他东西,现在无法确定。你看到我在这里可能遗漏了什么吗?
更新 1:
这是前端的调用
app.component 测试函数
handleSomeTests() {
let api = "test"
//standard get,returns HttpStatusCode.OK, "Standard Get executed"
console.log("===Standard Get===");
this.dataService.get<any>(api +'').subscribe(
(res) => {
console.log(res);
},
error => {
//error.message, error.name, error.ok, error.status, error.statusText, error.url
console.log(error);
}
);
}
和数据服务(尚未完成但已完成其基本工作)
import { Injectable } from '@angular/core';
import { HttpClient, HttpParams, HttpEvent } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class DataService {
baseApi: string = 'MWAPI';
baseUrl: string = 'http://localhost:3554/';
retries: number = 0;
constructor(private http: HttpClient) { }
/**
* A GET method
* @param url api url without leading / and MWAPI/ as well
* @param params pass empty, will cover stuff like ?x=1&y=2, instead use HttpParams pass as { params: { sessionTimeOut: 'y' } } or const params = new HttpParams().set('q', 'cironunes');
* @returns returns T string/number/model
*/
get<T>(url: string, params: any | null = null): Observable<T> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.get<T>(url, { params })
.pipe(retry(this.retries));
}
/**
* A POST method
* @param url api url without leading / and MWAPI/ as well
* @param body model posting
* @param params pass empty, will cover stuff like ?x=1&y=2, instead use HttpParams pass as { params: { sessionTimeOut: 'y' } } or const params = new HttpParams().set('q', 'cironunes');
* @returns returns T string/number/model
*/
post<T>(url: string, body, params: any | null = null): Observable<HttpEvent<T>> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.post<T>(url, body, params)
.pipe(retry(this.retries));
}
/**
* A PUT method
* @param url api url without leading / and MWAPI/ as well
* @param body model posting
* @param params pass empty, will cover stuff like ?x=1&y=2, instead use HttpParams pass as { params: { sessionTimeOut: 'y' } } or const params = new HttpParams().set('q', 'cironunes');
* @returns returns T string/number/model
*/
put<T>(url: string, body, params: any | null = null): Observable<HttpEvent<T>> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.put<T>(url, body, params)
.pipe(retry(this.retries));
}
/**
* A DELETE method
* @param url api url without leading / and MWAPI/ as well
*/
delete(url: string): Observable<object> {
url = `${this.baseUrl}${this.baseApi}/${url}`;
return this.http
.delete(url)
.pipe(retry(this.retries));
}
}
更新 2:
完整的错误响应
{…}error: error
bubbles: false
cancelBubble: false
cancelable: false
composed: false
currentTarget: null
defaultPrevented: false
eventPhase: 0
explicitOriginalTarget: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3554/MWAPI/test", readyState: 4, … }
isTrusted: true
lengthComputable: false
loaded: 0
originalTarget: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3554/MWAPI/test", readyState: 4, … }target: XMLHttpRequest { __zone_symbol__xhrSync: false, __zone_symbol__xhrURL: "http://localhost:3554/MWAPI/test", readyState: 4, … }
timeStamp: 88583total: 0type: "error"<prototype>: ProgressEventPrototype { lengthComputable: Getter, loaded: Getter, total: Getter, … }
headers: Object { normalizedNames: Map(0), lazyUpdate: null, headers: Map(0) }
message: "Http failure response for (unknown url): 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: null
<prototype>: Object { constructor: HttpErrorResponse() } app.component.ts:81:8
更新 3:
chrome 也在显示
Failed to load http://localhost:3554/MWAPI/test: The 'Access-Control-Allow-Origin' header contains multiple values '*, *', but only one is allowed. Origin 'http://localhost:57729' is therefore not allowed access.
我改为关注,使用 url 而不是 * 作为来源
var cors = new System.Web.Http.Cors.EnableCorsAttribute(origins: "http://localhost:57729", headers: "*", methods: "*")
现在 chrome 显示这个错误
Failed to load http://localhost:3554/MWAPI/test: The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:57729, *', but only one is allowed. Origin 'http://localhost:57729' is therefore not allowed access.
不喜欢allow origin的地方在哪里?
我也做了以下测试,结果还是一样。
更新 4:工作解决方案@VishalAnand 评论和 chrome 帮助解决了这个问题。
从 web.config 中删除了以下内容
移除了 webapiconfig 注册方法的限制,只留下前两行。
var cors = new System.Web.Http.Cors.EnableCorsAttribute(origins: "*", headers: "*", methods: "*");
config.EnableCors(cors);
//var constraints = new { httpMethod = new HttpMethodConstraint(HttpMethod.Options) };
//config.Routes.IgnoreRoute("OPTIONS", "*pathInfo", constraints);
它正在为 get 方法工作。我还没有测试过放置/发布/删除,希望它们也能正常工作。
最佳答案
请尝试删除 config.Routes.IgnoreRoute("OPTIONS", "*pathInfo", constraints);它应该有效。
关于c# - WebApi2 跨源请求被 Angular 前端阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51777866/
在我的应用程序中播放背景音乐时遇到问题。 首先,我在第一个 Storyboard View Controller 中的 ViewDidLoad 方法中开始播放音乐。即使我从一个页面跳转到另一个页面,它
我想跨行连接数组,然后进行不同的计数。理想情况下,这会起作用: WITH test AS ( SELECT DATE('2018-01-01') as date, 2 as value,
这是一个场景: Repo A 是一个包含大量模块和依赖项的怪异代码。安装起来并不容易。它由其他人维护并托管在 Github 上。 Repo A 包含一个非常有用的模块 X,并且几乎不依赖于 Repo
目前,我在一台服务器上运行了一个应用程序。有一个 crontab 设置,因此根据指定的规则,在某些时间运行任务。 现在,我正在考虑将我的应用程序迁移到 docker 容器中,以便我能够独立运行我的应用
我有一个全局表,我想在两个不同的 Lua 状态之间保持同步。根据我所阅读和理解的内容,唯一的方法似乎是,在我的 C 后端,在状态之间进行表的深层复制(如果表已被修改)。有没有更好的办法 ? 另外,我看
我们目前有一个 asmx webservice,它公开了一个方法来对 Sql 数据库进行各种更新,内部包装在 SqlTransaction 中。 我正在 WCF 中重写此服务,我们希望将现有方法拆分为
我是 Qt 的新手,所以请原谅这个问题的简单性,但我对 Qt 线程有点困惑。假设我有 3 个线程:主要的默认 GUI 线程和我自己创建的 2 个线程(称为 WorkerThread)。我的每个 Wor
我们的产品有一个 Restful API 和一个服务器渲染的应用程序(CMS)。两者共享数据库。两者都是用django编写的 两者所需的字段和模型并不是相互排斥的,有些仅针对 API,有些针对 CMS
我正在实现一个基于角色的访问控制系统,它具有以下数据库表。 groups --------- id (PK) name level resources --------- id (PK) name r
我有三个应用程序,为了便于管理,我希望将它们分开。他们按照建议作为 Plack 服务器运行 here , 代理在 nginx 后面。 我想有一个单独的应用程序来管理登录,并在所有其他应用程序之间共享该
我的主窗口上有一个 UIWebView。我可以通过我的第二个 View Controller 来控制它吗?如果可以的话你能给我举个例子吗? 最佳答案 是的,你可以。 “如何”是一个基本的 Cocoa/
我想制作一个小型应用程序,从连接到串行端口的设备收集数据,并将其通过 LAN 传递到另一个应用程序,后者将其存储在数据库中。 我已经在一台 PC 上的一个应用程序中完成了此操作,因此实际上会将应用程序
从主 AppDomain,我试图调用在不同 AppDomain 中实例化的类型中定义的异步方法。 比如下面的类型MyClass继承自 MarshalByRefObject并在新的 AppDomain
因为 LiveServerTestCase继承自 TransactionTestCase ,默认行为是在每个测试方法结束时删除测试数据。我想用LiveServerTestCase类,但保留方法之间的测
我正在开发我的第一个 WPF/MVVM 应用程序,但我在命令知识方面遇到了限制! 这是我的场景。 我有一个窗口——Customer.xaml。 它包含 2 个用户控件 查看CustomerSearch
这是我的 WPF 应用程序模型的简化版本: Employee +Name:string Client +Name:string +PhoneNumber:string Appointmen
我有一个 mercurial 存储库,它使用子存储库功能(如 .hgsub 文件中定义的)引入依赖项,但我正在努力让它在 TeamCity 中工作。 我启用了 mercurial_keyring 扩展
我正在尝试使用新的 Azure 虚拟网络公共(public)预览版的对等互连功能来加入我在两个不同订阅(即不同租户)上拥有的两个网络。这可能吗?我没有看到任何其他说法,但是当我尝试在 PowerShe
我有 2 个存储库。由于主干代码位于一个 protected 存储库中,因此我进行了 checkout ,然后 checkin 到另一个存储库(因为用户没有第一个 protected 存储库的权限)。
我有一个项目,其调用结构与此类似: 主要项目/应用 我的图书馆代码 别人的库代码 我的图书馆代码 一切都是用 C# 编写的,我可以访问“其他人的库代码”。他们的代码不包含在我的项目中,因为它是开源的而
我是一名优秀的程序员,十分优秀!