Mohammad Saad Abdul Rahim Mohammad Saad Abdul Rahim - 1 month ago 7
ASP.NET (C#) Question

Post data to Asp.net web api using Angular 2

I want to post data on my asp.net web api using angular 2 but i am getting these errors. I cannot figure out what is wrong with my code.
Error Screenshot

Asp.net Code

[ResponseType(typeof(User))]
public IHttpActionResult PostUser(User user)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}

db.Users.Add(user);
db.SaveChanges();

return CreatedAtRoute("DefaultApi", new { id = user.UserID }, user);
}


Angular 2 code

////////////////////////////////////////////////////////// Service ///////////////////////////////////////////////////////////

@Injectable()
export class TaskService {

private Url = 'https://jsonplaceholder.typicode.com/posts';

private handleError(error: any): Promise<any> {
debugger;
console.error('An error occurred', error); // for demo purposes only
return Promise.reject(error.message || error);
}
task;

constructor( private _http : Http) {
}

getItems()
{
var Promise =this._http.get(
'http://localhost:27353/api/Users')
.map(res=>res.json())
.toPromise()
Promise.then(taskFromServer => this.task = taskFromServer)
Promise.catch(this.handleError)
}

postitems(userId,username,userrole)
{
debugger;
let data = {
"UserName": username,
"UserRole": userrole

}
//let body = JSON.stringify(data);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });

return this._http
.post('http://localhost:27353/api/Users', JSON.stringify(data), {headers: headers})
.toPromise()
.then(res => res.json().data)
.catch(this.handleError);
}

private extractData(res: Response) {
let body = res.json();
return body.data || { };
}

}

///////////////////////////////////////////////Task Component /////////////////////////////////////////////////////
@Component({

selector: 'tasks',
providers: [TaskService],
template: `<h4> This is the Task in Angular </h4>
<Button class = "btn btn-primary" (click) = "OnClick()" > Click me </Button>


<input [(ngModel)] = "userId" >
<input [(ngModel)] = "username" >
<input [(ngModel)] = "userrole" >

<Button class = "btn btn-primary" (click) = "OnClick(userId,username,userrole)" > Submit </Button>

<div class="table-responsive" >


<table class="table" style="width:100%">
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
</tr>

<tr *ngFor = "let task of tasklist.task">
<td>{{task.UserID}}</td>
<td>{{task.UserName}}</td>
<td>{{task.body}}</td>
<td> <a class="btn btn-link" (click) = Edit(task) > Edit </a> </td>
</tr>

</table>

</div>

`
})

export class TasksComponent implements OnInit {

sample:string = ""

constructor(public tasklist: TaskService , private router: Router) { }

ngOnInit() {

this.tasklist.getItems();

}

OnClick(userId,username,userrole)
{
debugger;
this.tasklist.postitems(userId,username,userrole);
}

Edit(value)
{
debugger;
this.router.navigate(['/others' , value]);
}
}

Answer

The OPTIONS verb is probably from a cross-domain JavaScript request done by your browser. The OPTIONS is part of a pre-flight request the browser carries out to find out what is supported for cross-domain requests.

Try making the same POST from the Chrome extension Postman. As an extension to Chrome it does not follow the same CORS rules. If it works in Postman then this is a CORS issue and you need to enable CORS.

Follow the instructions here: https://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors.

Comments