Calling POST as URL ASP.NET web api - asp.net-mvc-4

I want to know how to test POST by typing in the url.
Here's my route Config
config.Routes.MapHttpRoute(
name: "myWebApi",
routeTemplate: "api/mywebapi/{action}/{ID}/{DeptID}",
defaults: new { Controller = "mywebapi", ID = #"\d+", DeptID = #"\d+" }
);
programmatically this is how I call POST
I have 3 text boxes and a button. When user clicks on the button the below program gets called
function parseform(button) {
var id = $("#ID").val();
var deptid = $("#DeptID").val();
var name = $("#Name").val();
var inputdata = {
id: id,
deptid: deptid,
name: name
}
if (button.attr('value') === "POST") {
postdata(inputdata);
} else {
console.log("ERROR");
}
}
function postdata(inputdata) {
$("#response").text("Posted");
$.ajax({
type: "POST",
dataType: "json",
url: "api/mywebapi/Post/",
contentType: "application/json",
data: JSON.stringify(inputdata),
xhrFields: {
withCredentials: true
},
success: function (data, status, xhr) {
$("#response").text(status+" - "+data)
},
error: function (xhr, status, error) {
var json = jQuery.parseJSON(xhr.responseText);
$("#response").text(status)
}
});
}
In the controller
[System.Web.Http.AcceptVerbs("POST")]
public void Post([FromBody]mywebapi value)
{
saves to database
}
Here's what I tested
http://localhost:222/api/mywebapi/Post/new newwebapi ({"id":"1","deptid":"2","name":"testing"})
I get error. How to test this?
thanks
R

Since it's a POST request, you can't test it in your browser by typing in an address (those are GET requests, which contain no body).
To test these types of things you can use something like Postman
or Rest Console (if you're using chrome), there's tons of these types of things in whatever your browsers extension store is called.
Some tools you can use are something like Fiddler
this will let you see what the requests and responses look like, and you can change/modify them as well, though it's probably a bit harder to use than something like PostMan or Rest Console (also more powerful)

Related

Shopify app with proxy extension PUT requests not working

I have managed to created an app proxy using this guide:
https://shopify.dev/tutorials/display-data-on-an-online-store-with-an-application-proxy-app-extension#handling-proxy-requests
I wanted to update the customer record using a form. On submission of form the below func would be invoked.
jQuery(function($) {
$('#enrollFormID').submit(function() {
var fname = $(FirstName).val();
var lname = $(LastName).val();
var emailID = $(email).val();
var pass = $(password).val();
event.preventDefault();
var data = jQuery(this).serialize();
console.log(data);
data = "form_type="+data;
$.ajax({
url: '/apps/subpath',
type: 'PUT',
data: data,
dataType: 'json',
success: function (data) {
console.info(data);
}
});
return true;
});
});
In the backend app, the below url is getting hit when the form gets submitted, but am not able to retrieve the form data values.
router.put('/test', async (ctx) => {
.....
}
Get request works fine, but with Put request am not able to retrieve the form data from the ajax call.
Can someone help me on this?

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);
}

Why page url changes after PUT method in Web API?

I am using Web API in a MVC Website. This is my Update action in the API controller:
public HttpResponseMessage PutProduct(int Id, ProductModel model)
{
HttpResponseMessage response = null;
if (ModelState.IsValid)
{
model.ProductId = Id;
if (model.Update())
response = Request.CreateResponse(HttpStatusCode.Created);
}
return response;
}
I call it using JQ AJAX from a partial view which is loaded in the Index.cshtml page. The code works fine and the index page does not get called again, instead, the new list is populated in the partial view itself. I am not calling Index page again. But after the response, the page url changes to show like this:
http://localhost:54820/Products/Index?ProdName=Chicken+Soup&Category=Chinese&Price=20
This is my AJAX:
function updateprod(product) {
$.ajax({
url: uri + '/' + product.ProductId,
type: 'put',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(product),
statusCode: {
201: function (data) { //accepted
loadlist();
}
}
})
.fail(function (xhr, textStatus, err) {
alert(err);
});
}
I want the URL to be like this, like what it was initially:
http://localhost:54820/Products/Index
Can anyone help ?
You should look at the response headers.
It seems that your response has a location header used by the user-agent to redirect to URL indicated in the response.
Besides that you should use 201 status-code for created resources, for update is better to use 200 (OK), how you can read in the w3c docs.
Hope it helps.

How to get the response after a POST request in CasperJS

I have this very simple code to read the response from a server endpoint after a post request. Actually I'm saving a data to a database and wait for a response before going to next step
casper.open('http://example.com/ajax.php, {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
});
on ajax.php file I'm trying to echo the POST request in a simple way.
this will let me know easily if I'm getting the right response from the server.
echo json_encode($_POST);
I tried these snippets but I'm unable to get the response.
casper.on('page.resource.received', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('http.status.200', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('resource.received', function(resp) {
this.echo(JSON.stringify(resp, null, 4));
});
I've been facing the same problem POSTing a query to ElasticSearch and I could not retrieve the results.
As far as I can understand if you want to retrieve the data echoed by your script the solution could be this:
this.echo(this.page.content);
or
this.echo(this.page.plainText);
in your function.
For example (my case with ElasticSearch):
/*
* SOME VAR DEFINITIONS HERE
*/
casper.start();
casper.then( function() {
// the next var is very specific to ElasticSearch
var elasticQuery = JSON.stringify (
{
'size' : 20,
'query' : {
'filtered' : {
'filter' : { 'term' : { 'locked' : false } }
}
},
'sort': { 'lastScrapeTime': { 'order': 'asc' } }
}
);
var elasticRequest = {
method: 'POST',
data: elasticQuery
}
this.thenOpen( <<YOUR URL>>, elasticRequest, function (response) {
// dump response header
require('utils').dump(response);
// echo response body
this.echo(this.page.content);
// echo response body with no tags added (useful for JSON)
this.echo(this.page.plainText);
});
}
);
casper.run();
As Roberto points out. You can use this.page.content to show the response. But you need to add the function(response) in your script. For example:
casper.open('http://example.com/ajax.php', {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
}, function(response){
if(response.status == 200){
require('utils').dump(this.page.content);
}
});
If you want to unit test a REST API, CasperJS is not necessarily the right tool.
CasperJS allows to observe a web browser which is running a web page.
So a more typical approach would be to use CasperJS to load a page that would call your REST API and you would assert the page behavior is correct (assuming the page would make something observable according the AJAX call response).

asp.net webapi validation

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.