这是我在asp core api中的操作:
[Route("[action]"), HttpPost]
[AllowAnonymous]
public async Task<ActionResult> GenerateToken([FromForm]OAuthTokenRequestDto tokenRequest, CancellationToken cancellationToken)
{
// Some Code
}
OAuthTokenRequestDto:
public class OAuthTokenRequestDto
{
public string grant_type { get; set; }
public string username { get; set; }
public string password { get; set; }
public string refresh_token { get; set; }
public string scope { get; set; }
public string client_id { get; set; }
public string client_secret { get; set; }
}
这是我的Login.Component.html:
<form class="form-signin" #f="ngForm" (ngSubmit)="signIn(f.value)">
<input type="username" id="inputEmail" name="username" ngModel class="form-control" placeholder="username" required autofocus>
<input type="password" id="inputPassword" name="password" ngModel class="form-control" placeholder="Password" required>
<input type="client_id" id="inputclient_id" name="client_id" ngModel class="form-control" >
<input type="refresh_token" id="inputrefresh_token" name="refresh_token" ngModel class="form-control" >
<input type="scope" id="inputscope" name="scope" ngModel class="form-control" >
<input type="client_secret" id="inputclient_secret" name="client_secret" ngModel class="form-control" >
<input type="grant_type" id="inputgrant_type" name="grant_type" ngModel class="form-control" placeholder="password">
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
Login.Component.ts:
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
import { Component } from '@angular/core';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent {
invalidLogin: boolean;
constructor(
private router: Router,
private http: HttpClient
) { }
signIn(credentials) {
return this.http.post('/api/Users/GenerateToken',
new OAuth(credentials.username,credentials.password)
)
.subscribe(result => {
if (result)
this.router.navigate(['/']);
else
this.invalidLogin = true;
});
}
}
class OAuth {
grant_type : string;
username : string;
password : string;
refresh_token : string;
scope : string;
client_id : string;
client_secret : string;
constructor (username: string, password : string)
{
this.username = username;
this.password = password;
this.client_id = "";
this.refresh_token = "";
this.scope = "";
this.client_secret = "";
this.grant_type = "password";
}
}
当我尝试将凭据发布到操作中时,出现415错误,但是当我[FromForm]
从操作中删除时,它会起作用。
我不知道问题是什么。
注意:我想[FromForm]
采取行动
如果您想通过表单字段发布数据,请尝试遵循以下代码段。
signIn(credentials) {
const formData = new FormData();
formData.append("username", credentials.username);
formData.append("password", credentials.password);
// other fields
return this.http
.post("/api/Users/GenerateToken", formData)
.subscribe(result => {
//code logic here
});
}
测试结果
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句