asp.net webapi validation - asp.net-mvc-4

I have an API Controller and call action from JS:
$('#create-se').on('click', function () {
var data = {};
$.ajax({
url: 'api/registration',
type: 'POST',
data: data,
dataType: 'json',
contentType: 'application/json',
success: function () {
}
});
});
public bool Post(UserRegistrationViewModel model)
{
if (!ModelState.IsValid) { return false; }
return true;
}
Model has few required properties and few StringLength. When I send data from js to controller ModelState.IsValid always returns true. I can't figure out how to solve it. Even if posted model is null, Model.IsValid is true anyway

http://codebetter.com/johnvpetersen/2012/04/02/making-your-asp-net-web-apis-secure/
This website has a better way of doing validation and using headers to send the token across and if it invalid it will return validation failed.

Related

How we can bind primitive value(string, int) into action's parameter when we are using Ajax in Asp.Net Core 3.1?

I am working on a web application using Asp.Net Core 3.1, i make ajax call(using axios library, method is POST):
<script>
axios({
url: '/home/test', // HomeController/Test Action
method: 'post',
data: {
abc: 123
},
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
</script>
in my HomeController i have appropriate action:
[HttpPost]
public IActionResult Test(string abc)
{
return Json(new { abc });
}
in this case binding doesn't work well even if i add [FromBody] attribute like:
[HttpPost]
public IActionResult Test([FromBody]string abc)
{
return Json(new { abc });
}
what is a solution in this case?
You can use FormData() to pass axios data to controller:
<script>
var bodyFormData = new FormData();
bodyFormData.set('abc', 123);
axios({
url: '/Home/test', // HomeController/Test Action
method: 'post',
data: bodyFormData,
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
</script>
Here is the test result:
Sometimes the binding FromBody can't parse the html content from the body. Try to change the parameter type from string to dynamic. It should hit your controller.
You can wrap your parameter into a class that has only that field and there the binding works.
Also you can take advantage of the action constraints and try that as well
HttpPost("{abc:string}")
Hope this help

How to call a method from API Controller using ajax

I want to call a method from API Controller using AJAX. I have tried the following
I have added one hidden field in the view (like what we are doing in mvc controller)
<input type="hidden" id="GetShoppingCartUrl" value="#Html.Action("GetShoppingCartUrl","Cart")"/>
Then I have written ajax
function GetShoppingCart() {
debugger;
var url = $('#GetShoppingCartUrl').val();
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
But here it is not getting the method, GetShoppingCartUrl from the API Controller CartController. I want to call that method, what changes make it happening ?
function GetShoppingCart() {
debugger;
var url = "Cart/GetShoppingCartUrl"
$.ajax({
type: "get",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function () {
}
});
}
you can directly put your actionlink in the url
Hope it helps. :)
Use this below code to get the url of your site in javascript and append it before the url in ajax call. e.g var url = baseUrl+ "Cart/GetShoppingCartUrl";
#{
string url = Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath;
if(url[url.Length-1]!='/')
{
url =url+ "/";
}
}
var baseUrl = '#url';
//alert(baseUrl);

Creating post web api 2 actions

I am currently attempting to do something that should be fairly straight forward, but to be honest is pretty far from it at the moment and its driving me a bit mad.
I've been consuming Get actions in my WebApi, however I'm trying to create Post actions in order to keep my mvc controllers clean however I can't for the life of me figure out why my get actions work as expected but my post action results in a 404
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using TamWeb.Models.api;
namespace TamWeb.Controllers.api
{
[Authorize]
[Route("api/[controller]")]
public class AdminController : Controller
{
[HttpPost]
public bool UpdateDetails([FromBody]DetailsViewModel model)
{
return false;
}
}
}
using System;
namespace TamWeb.Models.api
{
public class DetailsViewModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
}
The api controller is as simple as it gets and as per several other api questions instead of using string parameters I've created a model object and to follow other answers and what little out of date documentation I can find I consume the api as follows:
$(function() {
var firstname = $('#firstName').val();
var lastname = $('#lastName').val();
$.ajax({
url: "api/admin/UpdateDetails",
type: "POST",
data: JSON.stringify([firstname, lastname]),
success: function(data) {
console.log(data);
},
error: function() { console.log("error") }
});
});
As far as I can tell everything "should" work, however fiddler keeps telling me the url doesn't exist so now I'm at a loss as to whats wrong.
hopefully my answer can help you to deal with your question.
1.first issue you have to use "ApiController" instead "Controller"
2. [Authorize] <-- you have to get token key and then using it to get data from webapi
as following code, I will share you me simple code without Authorize,I wish it can solve your problems
client code
$("#read1").click(function () {
$.support.cors = true;
$.ajax({
crossDomain: true,
url: 'http://localhost:43520/api/Banners/',
datatype: "json",
contenttype: "application/json; charset=utf-8",
data: { id: 123 },
type: 'post',
error: function (xhr, status, errorThrow) {
alert(xhr.status);
},
success: function (data) {
alert(JSON.stringify(data));
}
});
});
server code
// GET: api/Banners/5
[ResponseType(typeof(Banners))]
public IHttpActionResult GetBanners(int id)
{
Banners banners = db.Banners.Find(id);
if (banners == null)
{
return NotFound();
}
return Ok(banners);
}

How to return partial view or Json result based on condition?

I have following code in the controller, here I want to return Partial View or Json Result to jquery. My problem is when this controller is hit jquery blocks the UI with some progress bar and waiting for response until it return. But when ModelState is false it return partial view which bypass jquery unblock UI. So this makes UI block forever.
[HttpPost]
public ActionResult Edit(Form form)
{
...
if (!ModelState.IsValid)
{
return PartialView("EditPartial", model);
}
return Json(new
{
Success = true,
Id = ID
});
}
How can I solve this problem?
Your controller method is behaving properly. You just need to modify your ajax call:
$.ajax({
url: '<your url>',
dataType: 'json',
success: function(data, textStatus, jqXHR) {
// You have the json result.
},
error: function(jqXHR, textStatus, errorThrown) {
// You have the partial view
}
});
An empty response is also is considered to be a failed json parse. Your controller method should either return a response of null or {} instead.
See the below url for more details of dataType and error
http://api.jquery.com/jQuery.ajax/

how to call this calling WCF method continuously

I have an ajax enabled WCF service method :
[OperationContract]
public string Test(string name)
{ return "testing testing." + name; }
and I am calling it with following code:
$(document).ready(function () {
var varData = $("#NewSkill").val();
$("#Button1").click(function () {
$.ajax({
type: "POST",
url: "TimeService.svc/Test",
data: '{"name" : "John"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
I want to call this method continuously after every 5 seconds using above code . How can I do this ?
Move the $.ajax(); part to a Javascript function say AjaxCall(). Create a javascript variable
var isActivated = false;
$(document).ready(function () {
while(isActivated){
setTimeout("AjaxCall()",3000);
}
}
);
$("#Button1").click(isActivated = true)
Hope this helsps...