我是Angular平台的学生开发人员。我有自己的API。我有这样的发布方法:
[HttpPost]
[Route("login")]
public async Task < ActionResult < User >> LoginUser([FromBody] User _user) {
var joinedUser = _context.Users.FirstOrDefault(u => u.loginName == _user.loginName && u.password == _user.password);
if (joinedUser == null) {
return NotFound();
}
var user = await _context.Users.FindAsync(joinedUser.userId);
return CreatedAtAction("GetUser", new {
id = _user.userId
}, user);
}
我还有一个角度服务可以登录。当我填写表单数据时,_user每次都已满。我的意思是我正确地接受了形式的价值。当我向用户发送具有API服务的用户时,我遇到了这样的错误:
这是我的Angular服务方法:
private httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'bearer example',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*'
}),
withCredentials: false
};
constructor(private http: HttpClient) {}
private apiUrl = "https://localhost:44365/api/User/login"
LoginUser(_user: User): Observable < User > {
return this.http.post < User > (this.apiUrl, _user, this.httpOptions).pipe(
tap(data => console.log(JSON.stringify(data))),
catchError(this.handleError)
);
}
这是我的主要部分:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddCors();
services.AddDbContext<TwitterAPIContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//app.UseCors(options => options.WithOrigins("https://localhost:4200").AllowAnyMethod().AllowAnyHeader());
app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
app.Use(async (ctx, next) => {
await next();
if (ctx.Response.StatusCode == 204)
{
ctx.Response.ContentLength = 0;
}
});
app.UseHttpsRedirection();
app.UseMvc();
}
怎么了?您能帮我解决这个问题吗?
答案 0 :(得分:0)
主要问题是您的.NET方法签名:
public async Task<ActionResult<User>> LoginUser([FromBody]User _user)
参数User
不能在此处使用,并且不应使用,因为您没有传递任何参数。 HttpHeaders
不能用作参数。
您需要的是方法(或控制器类)上的[Authorize]
属性,该属性将为您验证承载令牌,如果承载令牌无效,则返回401。您无需手动检查凭据是否正确。
我建议您按照Microsoft的this指南进行操作,以使令牌验证在您的.NET项目中正常工作。
希望这会有所帮助!