我使用 Visual Studio 15 創建了一個應用程序,使用 ASP.NET Web api 作為后端,在前端使用 Angular 6。我只是想根據數據庫中的數據在前端顯示/添加/刪除用戶。我使用 Angular 6 中的 HttpClient 和 GET-Request 來顯示用戶數據工作正常。我嘗試以相同的方式實現 POST/DELETE 請求。這是來自 Angular 的調用:deleteUser(id: number): Observable<{}> { const url = `${this.userURL}/${id}`; return this.http.delete(url, { withCredentials: true }) .pipe( catchError(this.handleError('deleteData')) );}web API:我在 Global.asax.cs 中處理了預檢請求:void Application_PreSendRequestHeaders(Object sender, EventArgs e) { var origin = Request.Headers.Get("Origin"); var validOrigins = ConfigurationManager.AppSettings["allowedCorsOrigins"].Split(','); if (validOrigins.Any(o => o == origin)) { Response.StatusCode = (int)HttpStatusCode.OK; Response.Headers.Set("Access-Control-Allow-Origin", origin); Response.Headers.Set("Access-Control-Allow-Credentials", "true"); Response.Headers.Set("Access-Control-Allow-Headers", "Access-Control-Allow-Headers, access-control-allow-credentials, access-control-allow-headers, access-control-allow-methods, access-control-allow-origin, ontent-type, Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers, Authorization"); // "Content-Type, Accept, Authorization, withcredentials, Prefer" Response.Headers.Set("Access-Control-Expose-Headers", "Claims, *"); Response.Headers.Set("Access-Control-Allow-Methods", "GET,PUT,POST,OPTIONS,PATCH,DELETE"); } }
ASP NET web api POST/DELETE(Angular 6 HttpClient-)
慕工程0101907
2022-06-19 16:36:34