我正在尝试使用Angular调用WebAPI,但是遇到了未经授权的凭据问题。它在IE中工作正常,但在Chrome和FF(401未授权)中,凭据不会被转发。
我认为解决方案是将默认凭据添加到Angular的调用中,但我不知道该怎么做,或者可能还有其他解决方案。
Angular调用
import {Http} from 'angular2/http';
import {Injectable} from 'angular2/core';
import 'rxjs/Rx';
@Injectable()
export class MyListService{
constructor(private _http: Http) { }
getMyList() {
//return an observable
return this._http.get('http:////localhost:2311/api/MyListApi')
.map((response) => {
return response.json();
});
//.retry(3);
}
}
答案 0 :(得分:0)
您可以尝试这种方式:
public static void partnerStmt(ArrayList<Integer> keys, int age, int sex, int range){
int amount = keys.size();
int aageMin = alter - range;
int ageMax = alter + range;
int[][] storeArr = new int[amount][2];
if (ageMin < 18)
ageMin = 18;
String select = "SELECT ID FROM individuen WHERE Age BETWEEN "
+ ageMin +" AND "+ ageMax + " AND Family IS 2 AND Partner IS NULL AND Sex "
+ "IS " + sex + " ORDER BY RANDOM() LIMIT " +amount+";";
try {
Statement stmt = DBController.connection.createStatement();
ResultSet rs = stmt.executeQuery(select);
for (int i = 0; i < anzahl; i++){
int idColumn = rs.findColumn("ID");
int idPartner = rs.getInt(idColumn);
storeArr[i][0] = keys.get(i);
storeArr[i][1] = idPartner;
rs.next();
}
PreparedStatement person = DBController.connection.prepareStatement(
"UPDATE individuen set Partner = ? WHERE ID = ?");
for (int i = 0; i < amount; i++){
person.setInt(1, storeArr[i][0]);
person.setInt(2, storeArr[i][1]);
person.addBatch();
}
person.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
}
}
答案 1 :(得分:0)
我也有这个问题。我的Angular2-rc4应用程序在另一个域上调用.NET Core 1.0.0 WebAPI应用程序。发布此应用程序以防其他域名。
如其他人所述,在Angular2中传递withCredentials为真:
getUser() {
return this.http.get(this._apiUrl + "/account/GetUser", { withCredentials: true })
.toPromise()
.then(response => response.json().data)
.catch(this.handleError);
}
在您的WebAPI项目中,您可以在Startup.cs(而不是web.config)中设置CORS策略:
public void ConfigureServices(IServiceCollection services)
{
var corsBuilder = new CorsPolicyBuilder();
corsBuilder.AllowAnyHeader();
corsBuilder.AllowAnyMethod();
corsBuilder.AllowAnyOrigin();
corsBuilder.AllowCredentials();
services.AddCors(options =>
{
options.AddPolicy("AllowAll", corsBuilder.Build());
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("AllowAll");
}
当然,根据您应用的需求设置您的政策,这只是允许所有测试。示例here和官方.NET Core文档here提供了更多详细信息。