我在使用Asp核心Web API的Angular 4應用程序,我使用不同的端口在locahost上進行測試。我的WebApi需要Windows身份驗證(需要獲取登錄用戶名)。所有使用GET的調用工作,但不幸的是,我不能讓POST工作。我對CORS的WebAPI設置:Asp.net Core CORS與GET協同工作,但不支持POST
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddApplicationInsightsTelemetry(Configuration);
services.AddDbContext<CatalogContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddCors(options =>
{
options.AddPolicy("AllowAll", builder =>
{
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
services.AddMvc();
}
和角4客戶端嘗試發佈文件
fileChange(event) {
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
let formData: FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
/** No need to include Content-Type in Angular 4 */
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers, withCredentials: true });
this.http.post("http://localhost:495/api//upload",formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
我的錯誤:
的XMLHttpRequest無法加載http://localhost:495/api//upload。請求的資源上沒有「Access-Control-Allow-Origin」標題。因此不允許訪問原產地'http://localhost:4200'。響應有HTTP狀態代碼500。
和響應頭
的Content-Length:0 日期:孫老師,2017年8月13日13時13分09秒GMT 持久驗證:真 服務器:紅隼 X -Powered-者:ASP.NET X-SourceFiles:= UTF-的8B QzpcU291cmNlIENvZGVcUGFydG5lcnNoaXBDYXRhbG9nXFBhcnRuZXJzaGlwQ2F0YWxvZ1xQYXJ0bmVyc2hpcENhdGFsb2cuV2ViQXBpXGFwaVx1cGxvYWQ = =
任何幫助,將不勝感激????!
檢查http://enable-cors.org。它看起來像你添加Cors的方式不起作用。檢查Chrome網絡選項卡是否有http請求。單擊請求查看請求和響應詳細信息。而不是通過你的應用程序調用,檢查與提琴手或鉻擴展像郵遞員或高級休息。您也可以嘗試單獨啓用個別類,方法或web.config中的cors。 – Amit
請發佈您的異常堆棧/消息。當發生ASP.NET Core中的異常時,異常中間件將**清除頭文件**,因此CORS頭文件會丟失。看看是什麼導致異常並解決異常,那麼它應該可以工作,發生異常時返回HTTP代碼500 – Tseng
您可以確認'UserCors'在'Configure'方法中的任何'UseMvc'調用之前嗎? – regnauld