asp.net web api 2 attribute route is not found - asp.net

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="

Related

ASP.Net MVC Getting HTTP 400 with ajax post request

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()
},

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.

Json PaserError when calling web service

I am getting this "Json ParserError" in chrome console when looping through the response returned by web service. I am using dataType: jsonp as i am trying to call cross domain ajax call in development environment, BUT stuck with this error.
$.ajax
function callajax1() {
$.ajax({
url: "http://www.sample.com/Integration/PhotoCompetitionHelper.asmx/SayHello",
data: "",
dataType: 'jsonp',
type: 'POST',
contentType: "application/json; charset=utf-8",
jsonpCallback: 'showResult',
success: function (data) {
console.log(data.d)
},
error: function (data, status) {
console.log("FAILED:" + status);
}
});
}
function showResult(data) {
console.log(data.d);
}
WebService
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string SayHello()
{
return "Hello";
}
JSON Response
{"d":"Hello"}
ERROR
FAILED:parsererror
You are getting the parser error because when your dataType is jsonp, it expects a script and not json. Try to include a callback function.

$.ajax success not executing

I have in my .js file a function that call a webservices method called getStudents:
[WebMethod(Description = "white student list")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<Job> getStudents(long classId)
{
return (new classManager()).getStudents(classId);
}
the method is callled like:
function loadStudents() {
var parameters = JSON.stringify({ 'classId': 0 });
alert(parameters);
$("#ProcessingDiv").show('fast', function() {
$.ajax({
type: "POST",
url: "myWebService.asmx/getStudents",
data: parameters,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
$("#ProcessingDiv").hide();
var students= response.d;
alert('yes');
},
error: function(request, status, error) {
alert(request.responseText);
}
,
failure: function(msg) {
alert('somethin went wrong' + msg);
}
});
});
}
$(document).ready(function() {
loadStudents();
});
when i debug,the service web method is executed successfully but i don't get my alert('yes') and neither msg error.
What's wrong?
If you're returning (serialized to JSON) List of objects, then in response you will get JS array of JS objects, so (assuming Job has property p) try response[0].p for p value from first element.
note: I don't know ASP.NET, so maybe response is serialized in another way, thats where tools like Firebug (or other browsers Dev tools) are extremely useful - because you can look how exactly you'r http requests and responses looks like.
ps. And change alert to console.log and look for logs in Firebug console - its better than alert in many, many ways ;]

converting object variable to json string for asp.net page method

This is probably a very simple task to perform but I'm taking the risk to ask anyway.
I have an object variable that looks like this:
var MyObj = {"Param1": "Default",
"Param2": "test",
"Param3": 3 };
I'm using ASP.net and I'm looking to pass this object to a page method via jquery.
So far, I have this javascript code:
function LoadObject () {
var TheObject = MyObj.toString();
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: TheObject,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
I have a page method set up in the .cs file and I put a breakpoint in it but it never gets there; nothing happens.
Please let me know what changes I need to make to get this to work.
Thanks.
You need to serialize TheObject into a JSON string, and ensure that the GetCount method accepts an object with the same signature as TheObject.
I use the jQuery.JSON library to do this so that my syntax becomes:
data: "{ methodParameterName: " + $.toJSON(TheObject) + " }"
I use this library, but you can acheive the same thing with any other library in a similar manner
The first thing that you need to know is that you need to match your method name with your url
for example if your method on your code behind is named "calculate", your url must be something like this "../Pages/TestPage.aspx/calculate"
other thing that you need to keep in mind is the parameters of your method, the names and the types of your parameters must match in you ajax call and your method (code behind)
if the sign of your method is something like this
[WebMethod]
public void Calculate(string data){
// your code here
}
Your ajax call must be like this:
function LoadObject () {
var objetoJson = {
data: JSON.stringify(MyObj)
};
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/Calculate",
data: objetoJson ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFn,
error: errorFn
});
};
This section is so important:
var objetoJson = {
data: JSON.stringify(MyObj)
};
the name "data" is the name of your parameter in your method (code behind) and "JSON.stringify" is a helper functions already defined on your browser to convert and object to string
Hope this helps
Take a look at this thread: JSON stringify missing from jQuery 1.4.1?
Abstract: jQuery doesn't have a native method to do it. But there are many plugins out there.
EDIT
Sample C# code receiving your JSON object:
[WebMethod]
public static int GetCount(GetCountParams p)
{
// ... Do something with p.Param1, p.Param2, etc.
return 0;
}
public class GetCountParams
{
public string Param1 { get; set; }
public string Param2 { get; set; }
public string Param3 { get; set; }
}
EDIT 2
Sample jQuery AJAX call using that object as parameter:
$.ajax({
type: "POST",
url: "../Pages/TestPage.aspx/GetCount",
data: "{ p: '" JSON.stringify(MyObj) + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json"
});

Resources