ASP.Net MVC Getting HTTP 400 with ajax post request - asp.net

I am trying to post some simple data with ajax from my view to controller. When I switch it to HttpGet it works fine, but when trying httppost I always get error 400.
Here is my view code:
#Html.Hidden("postSettings", Url.Action("MethodName", "MyController"))
$.ajax({
url: $("#postSettings").val(),
type: "POST",
data: JSON.stringify(11),
dataType: "json",
contentType: "application/json",
success: function (_result) {
console.log("success")
},
error: function (e) {
console.log(e);
}
});
And code in my controller:
[HttpPost]
public IActionResult MethodName(object value)
{
return Ok();
}

I did not noticed that I have global filter applied
services.AddMvc(options =>
{
options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
});
,adding the CSRF token fixed the problem.
I just added this code to my view:
<script type="text/javascript">
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
</script>
And to the ajax request:
headers: {
RequestVerificationToken: gettoken()
},

Related

how to get data from WebMethod in angular2

In Javascript using Ajax
$.ajax({
type: "Get",
url: "AttendanceMaster.aspx/GetDistinctBatch",
data: "{}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function(response) {
},
error: function(response) {
alert("(allstudent )" + response.status + ' Error ' + response.statusText);
}
});
tried following for angular2
return this._http.get("AttendanceMast.apsx/GetDistinctBatch")
.map((response) => response.toString());
it returns
{ "_isScalar": false, "source": { "_isScalar": false }, "operator": {} }
C#
[System.Web.Services.WebMethod]
public static string GetDistinctBatch()
{
return "welcome Angular 2";
}
1) how to use in angular2?
See Error below
Your method is just returning Observable, they will just sit as a function. Observable are lazy in nature. They wouldn't get executed until you subscribe to them.
AttendanceMast() {
return this._http.get("AttendanceMast.apsx/GetDistinctBatch")
.map((response) => response.toString()); //better do it response.json();
}
myService.AttendanceMast().subscribe(
data => console.log(data);
)
dataservice
getwithParamter(): Observable<JSON> {
this.headers = new Headers();
this.headers.append('Content-Type', 'application/json; charset=utf-8');
let options = new RequestOptions({
method: RequestMethod.Post,
url: "AttendanceMast.aspx/HelloWorldss",
headers: this.headers,
body:{program: 'pravin'} //same like data: "{}" in ajax
});
return this._http.request(new Request(options)).retry(2)
.map((response: Response) => response.text())
.do(data => console.log('All: ' + JSON.stringify(data)))
.catch(this.handleError);
}
handleError(error: any) {
console.error('An error occurred', error);
return Promise.reject(error.message || error);
}
C#
[System.Web.Services.WebMethod]
public static string HelloWorldss(string program)
{
return "welcome Angular" + program;
}
call
this.dataService.getwithParamter().subscribe(
tradeshows => this.getwithparamter = tradeshows,
error => console.error('Error: ' +error)
);
print this variable showing your output this.getwithparamter
I assume you are using the standard configuration for a WebService. If so, I believe your problem is that your are using the inbuilt rest capability of Angular2 to access a WebService, aka a Soap service, returning xml soap envelopes. Hence the 404.
Unfortunately, you have a bit more work to do to make it work than if you were accessing a rest service.
Have a look at angular2-soap on github. It should get you on the right track.

With Cookie Auth in ASP.NET 5 Identity, how to get WebAPI to return 403

I created a trivial webapi controller with the authorize tag as below. I call it with jquery when I'm not authenticated and I get in the response the message
{"Message":"Authorization has been denied for this request."}
but that carries a 200 success which means the jquery error handler success gets called.
using WebAPI 2, I want a 403 thrown when not authorized, not a 200. How can I achieve this?
Controller File:
public class TenantWebApiController : ApiController
{
// GET: api/TenantWebApi
[Authorize]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
...
Index.cshtml
$(document).ready(function () {
$.ajax({
url: '/api/TenantWebApi',
type: 'GET',
dataType: 'json',
data: {
firstName: 'Peter',
lastName: 'Kellner'
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred');
},
success: function(data, textStatus, jqXhr) {
alert('success');
}
});
});

I get "Get" web service instead of "POST" web service

I have used this post Jquery Ajax Posting json to webservice to send data to the server via "POST" web service,but it has been traited like a "Get"
in "Network" section of the browser,this is what I get:
this is my code for the web service(ASP.net):
// Insert Student
[Route("api/Students/ajout")]
[System.Web.Http.ActionName("Create")]
public async Task<HttpResponseMessage> Post(Student value)
{
try
{
if (ModelState.IsValid)
{
_StudentService.Insert(value);
var response = Request.CreateResponse<Student>(HttpStatusCode.Created, value);
await _unitOfWorkAsync.SaveChangesAsync();
return response;
}
else
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, "Model state is invalid");
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message);
}
}
and this is my code (AngularJS)
$.ajax({
type: 'POST',
url : 'http://localhost:50001/api/Students/ajout',
dataType: 'jsonp',
contentType: "application/json; charset=utf-8",
data: { FirstName: ''+$scope.FirstName+'', LastName: ''+ $scope.LastName+'' , Email: ''+ $scope.Email+'' , DropOut:'' +$scope.dropout.value1+'' , Live: ''+$scope.live.value2+'' , ClassId:2, ImageId:1}, // On fait passer nos variables, exactement comme en GET, au script more_com.php
success: function(data){
console.log("success");
},
failure: function(errMsg) {
console.log(errMsg);
}
});
have you please any idea how can I deal with this problem,thanks a lot for help
Update:
I have changed the code like that:
$.ajax({
type: 'POST',
url : 'http://localhost:50001/api/Students/ajout',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: { FirstName: ''+$scope.FirstName+'', LastName: ''+ $scope.LastName+'' , Email: ''+ $scope.Email+'' , DropOut:'' +$scope.dropout.value1+'' , Live: ''+$scope.live.value2+'' , ClassId:2, ImageId:1}, // On fait passer nos variables, exactement comme en GET, au script more_com.php
success: function(data){
$rootScope.usersData = angular.toJson(data);
console.dir($rootScope.usersData);
console.log("success");
},
failure: function(errMsg) {
console.log(errMsg);
} });
but I get this error:
XMLHttpRequest cannot load http://localhost:50001/api/Students/ajout. Response for preflight has invalid HTTP status code 405
In your api try to remove [Route("api/Students/ajout")] and instead of [System.Web.Http.ActionName("Create")] put [HttpPost].
In your controller, I advise you to use angularjs queries rather than the ajax requests.
this request should run if you edit your api controller:
var request = $http({
url:"api/students/",
dataType:"json",
method:"POST",
data:JSON.stringify(student),//you can send directly the object student if is well-trained or use params:{'name':value, ...}
contentType:"application/json; charset=utf-8"
});
And in your Api controller to recovered your object if you use JSON.stringify change your method for :
[HttpPost]
public void CreateStudent([FromBody]Student value)
{
...
}
I don't know if you do, but in your html instead of bind the property firstname on your input, bind student.firstName. Like this, you can recover directly $scope.student with the property $scope.student.firstName instead of recover each property one by one. And so send directly the object like I put in example.
So I hope this will helpfull.
Keep me informed of your progress. Have nice day.

Controller post returning View but doesn't display the View

I have a View.cshtml file in ViewController which has a hyperlink. Upon clicking the link, I call an ajax request to POST to a GreetingController action:
[HttpPost]
public async Task<ActionResult> Welcome(MyModel model)
{
ActionResult result = null;
Task<bool> createTask = Helper.Create(model);
try
{
bool success = await createTask;
if (success)
{
result = View();
}
else
result = new HttpNotFoundResult("Specified resource was not found.");
}
catch
{
result = View("Error");
}
return result;
}
If the method in the POST is succesful, I set the result to the View property. I have a Welcome.cshtml view for this Action and I was expecting it to display that but it doesn't. Instead of returning View, I tried returning a RedirectToAction and created a GET version of the Welcome action, but still it didn't show. Can someone explain what I am doing wrong?
EDIT:
The AJAX call:
$.ajax({
type: "POST",
url: "/greeting/welcome",
data: JSON.stringify(model),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (result) {
},
error: function (xhr, err) {
}
});
Also, the return call above was originally "return View()". I've changed it to "return result".

asp.net web api 2 attribute route is not found

I have this route in an API controller called Recruiting:
ResponseType(typeof (int))]
[Route("Recruiting/setprimary/")]
public async Task<IHttpActionResult> PutUpdatePrimary(string userId, string orgId)
{
return Ok();
}
I am trying to hit this routing via ajax like so:
self.updatePrimary = function () {
var orgKey = self.selectedOrgKey();
alert(orgKey);
$.ajax({
type: "PUT",
contentType: "application/json; charset=utf-8",
url: "/Recruiting/setprimary/" + "?userId=" + userId + "&?orgId=" + orgKey,
data: null,
dataType: "json",
success: function (data) {
bootbox.alert('Changes saved successfully.');
},
error: function (err) {
bootbox.alert('An error occured while trying to set primary organisation. Please try again :/');
}
});
return true;
};
Fiddler is saying it cannot find the route. What do I have wrong here?
Looks like you have a typo in your request url: Instead of "&?orgId="..it should be "&orgId="

Resources