我正在使用asp.net webapi 2从角度2发出请求 当我运行我的应用程序。它给我上面的错误信息 我在fiddler中检查了它的回复
我在谷歌搜索解决方案,并根据建议进行了更改,但仍然面临同样的错误。 Asp.net网络API代码为: -
public void postvalidUser(string UserName,string Password)
{
try
{
var login = uData.Users.Where(x => x.UserName == UserName).ToList();
if (login != null && login.Count > 0)
{
foreach (var log in login)
{
if (log.UserName == UserName && log.Password == Password)
{
Console.WriteLine("login ok");
}
}
}
else
{
Console.WriteLine("login fail");
}
}
catch (Exception ex){
Console.WriteLine(ex);
}
}
login.servuce.ts代码
@Injectable()
export class LoginService {
constructor(private _http: Http) { }
postvalidUser(UserName: string, Password: string) {
const users = { UserName: UserName, Password: Password };
let body = JSON.stringify(users);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({headers: headers });
return this._http
.post("http://localhost:65440/api/User", users, options)
.map(result => result.json());
}
}
login.component.ts
export class LoginComponent implements OnInit {
constructor(private _loginservices: LoginService) { }
ngOnInit() {
}
OnClick(UserName: string, Password:string) {
this._loginservices.postvalidUser(UserName, Password)
.subscribe(users => console.log(users));
}
login.component.html
<div>
<table>
<tr>
<td>UserName</td><td><input [(ngModel)]="UserName" /></td>
</tr>
<tr><td>Password</td><td><input [(ngModel)]="Password" /></td>
</tr>
<tr>
<td></td><td><button class="btn btn-primary" (click)="OnClick(UserName.value,Password.value)">Submit</button></td>
</tr>
</table>
</div>
如果我的代码中有错误,请纠正我
答案 0 :(得分:0)
您的问题与您的API有关。您缺少HttpPost
动词,并且您的方法需要返回类型而不是void
。您还需要一个模型来接受您的值
public class User
{
public string UserName {get; set;}
public string Password {get; set;}
}
然后在控制器中使用该模型
[HttpPost]
public IHttpActionResult postvalidUser(model User)
{
//Do whatever needs to be done.
//if log in is successful then return Ok()
return Ok();
//if log in is NOT successful then return BadRequest()
}
您的服务将如下所示
postvalidUser(UserName: string, Password: string) {
let users = { UserName: UserName, Password: Password };
return this._http
.post("http://localhost:65440/api/user", users)
}
<强>组件强>
OnClick(UserName: string, Password:string) {
this._loginservices.postvalidUser(UserName, Password)
.subscribe(users => console.log(users),
error => {
//check the error code here, if it 400 then log in information supplied was incorrect
});
}
不需要标头,也不需要JSON.Stringify
。