Menu
  • HOME
  • TAGS

ASP.net MVC HTTP Request error with payload

Tag: asp.net,json,asp.net-mvc,http

I am creating an ASP.net MVC website with a RESTful API to a SQL database. I have implemented a controller which holds the HTTP commands.

One of the commands is a POSTcommand:

     // POST: api/PoolTests
     [ResponseType(typeof(PoolTest))]
     public IHttpActionResult PostPoolTest(PoolTest poolTest)
     {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.PoolTests.Add(poolTest);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = poolTest.Id }, poolTest);
     }

I am using Fiddler to test out the function and I am getting some strange results. According to the automatically generated API documents the request format should be JSON with this structure (These are the fields to the connect SQL database):

               {
                 "Id": 1,
                 "SiteID": "sample string 2",
                 "Date": "sample string 3",
                 "Tub": "sample string 4",
                 "par1": 5.1,
                 "par2": 6.1,
                 "par3": 7.1,
                 "par4": 8.1
               }

In the fiddler composer I select POST and http://localhost:53660/api/PoolTests and the JSON payload {"Id": 1,"SiteID": "sample string 2", "Date": "sample string 3","Tub": "sample string 4","par1": 5.1, "par2": 6.1,"par3": 7.1,"par4": 8.1}

This results in a HTTP 400 error code.

If I send the same request with no JSON (payload) then it breaks at the line db.PoolTests.Add(poolTest); because the payload is null.

With payload if I place a break point at line if (!ModelState.IsValid) the breakpoint is never reached. It is almost like with payload the actual HTTP command is not being recognised.

Any thoughts - I appreciate that there may be some details missing.

ADDED: PoolTest Class

public class PoolTest
{
    public int Id { get; set; }
    public string SiteID { get; set; }
    public string Date { get; set; }
    public string Tub { get; set; }
    public double par1 { get; set; }
    public double par2 { get; set; }
    public double par3 { get; set; }
    public double par4 { get; set; }
}

FIDDLER Screenshot Added:

I have added the content-type and now I hit the breakpoint, but the Pooltest is reported as being null

enter image description here

Best How To :

You need to move the data to the Request Body. In Fiddler it would be a separate input box (below the one in your screenshot).

Your Headers for POST http://localhost:53660/api/pooltests become:

User-Agent: Fiddler
Host: localhost:53660
Content-Type: application/json
Content-Length: 140

The headers Content-Type should be application/json and the Content-Length will be computed for you. You are defining a header data which isn't correct.

In the Request Body you can paste your data

{"Id": 1,"SiteID": "sample string 2",   "Date": "sample string 3","Tub": "sample string 4","par1": 5.1, "par2": 6.1,"par3": 7.1,"par4": 8.1}

You can leave your action signature alone but [FromBody] is helpful when you want to add parameters to the URL.

[ResponseType(typeof(PoolTest))]
public IHttpActionResult PostPoolTest([FromBody] PoolTest poolTest)
{
    ...
}

An AJAX request with jQuery would look like this:

$.ajax({
    url: "http://localhost:53660/api/pooltests",
    method: "POST",
    data: { "Id": 1, "SiteID": "sample string 2", "Date": "sample string 3", "Tub": "sample string 4",
            "par1": 5.1, "par2": 6.1, "par3": 7.1, "par4": 8.1 }
})
.done(function(result) {
    console.log("success", result);
})
.fail(function(xhr, txtStatus) {
    console.log("error", txtStatus);
});

'utf8' codec can't decode byte 0xf3

python,json,character-encoding

Your file is not encoded in UTF-8, and the error occurs at the fp.read() line. You must use: import io io.open(filename, encoding='latin-1') And the correct, not platform-dependent usage for joining your paths is: os.path.join(root, f) ...

Link to another resource in a REST API: by its ID, or by its URL?

json,api,rest,api-design,hateoas

DO include absolute entity URIs in your responses (such as /customers/12 or even http://www.example.com/customers/12). DO NOT include just an entity's ID (such as 12) in a response, because that way you're forcing clients to put together resource URIs themselves. In order to do that, they would need to have prior...

Use JSON file to insert data in database

javascript,json,mongodb,meteor,data

Simple use underscores _.extend function. Like this: var newProfile = _.extend( JSON.parse(Assets.getText('test.json')), {user: id} ) Profiles.insert(newProfile) ...

Parsing Google Custom Search API for Elasticsearch Documents

json,python-2.7,elasticsearch,google-search-api

here is a possible answer to your problem. def myfunk( inHole, outHole): for keys in inHole.keys(): is_list = isinstance(inHole[keys],list); is_dict = isinstance(inHole[keys],dict); if is_list: element = inHole[keys]; new_element = {keys:element}; outHole.append(new_element); if is_dict: element = inHole[keys].keys(); new_element = {keys:element}; outHole.append(new_element); myfunk(inHole[keys], outHole); if not(is_list or is_dict): new_element = {keys:inHole[keys]}; outHole.append(new_element);...

Unable to find the auto created Database

c#,asp.net,asp.net-mvc,entity-framework

If you don't specify a database name then the connection will use the default database for the user, in this case it's integrated security so it's your Windows login. As you likely have full system admin on the server the default database will be master so you will find all...

Creating a viewmodel on an existing project

c#,asp.net,asp.net-mvc

You are using a namespace, your full type name is Project.ViewModel.ViewModel (namespace is Project.ViewModel and class name is ViewModel) so use this using instead: @model Project.ViewModel.ViewModel ...

Check for duplicates in JSON

javascript,jquery,json,duplicates

var asset = [ { value1: "1", value2: "2", value3: "3" }, { value1: "1", value2: "5", value3: "7" }, { value1: "6", value2: "9", value3: "5" }, { value1: "6", value2: "9", value3: "5" } ]; function countEqual(oo, pp) { var count = 0; oo.forEach(function (el) { var i,...

SQL Server / C# : Filter for System.Date - results only entries at 00:00:00

c#,asp.net,sql-server,date,gridview-sorting

What happens if you change all of the filters to use 'LIKE': if (DropDownList1.SelectedValue.ToString().Equals("Start")) { FilterExpression = string.Format("Start LIKE '{0}%'", TextBox1.Text); } Then, you're not matching against an exact date (at midnight), but matching any date-times which start with that date. Update Or perhaps you could try this... if (DropDownList1.SelectedValue.ToString().Equals("Start"))...

Third-party security providers like Google, Twitter etc. in ASP.Net

asp.net,authentication

No, you cannot enter any string. You will need to register with each provider to get the parameters that you need. See http://www.asp.net/web-api/overview/security/external-authentication-services for instructions on how to do this....

Show/hide tinymce with radio buttons

c#,asp.net,asp.net-mvc,tinymce

Your missing an @symbol for the id attribute: Modify your script as well like this: ***EDIT some thing seems off about the radio buttons only one should be checked and they should have the same name ** you can use the # to denote and ID in Jquery by the...

Replacing elements in an HTML file with JSON objects

javascript,json,replace

obj.roles[0] is a object {"name":"with whom"}. you cant replace string with object. you need to refer to property "name" in the object obj.roles[0].name Another problem is that var finalXML get a new value every line. you need to add a new value to the variable, not replcae it. var finalXML...

do calculation inside JSONArray in Java

java,arrays,json

Here's what I would do. Replace <JSON STRING HERE> with the JSON String you were going to parse: ArrayList<ArrayList<Integer>> resultList = new ArrayList<ArrayList<Integer>>(); JSONArray arr = new JSONArray(<JSON STRING HERE>); for(int i = 0; i < arr.length(); i ++) { JSONObject obj = arr.getJSONObject(i); JSONArray valueArray = obj.getJSONArray("values"); ArrayList<Integer> dataList...

WCF service architecture query

asp.net,architecture,wcfserviceclient

As long as you are able to use the exact same contract for all the versions the web application does not need to know which version of the WCF service it is accessing. In the configuration of the web application, you specify the URL and the contract. However, besides the...

Server side session in asp.net

asp.net,web-services,session

You've got a quotes problem, fix it like this: <% Session["path"] = "'" + vr_ + "'"; %> EDIT 1: Javascript and ASP.NET are not the same, so you cannot access the variables, so you can't do it on the client side. You must send something to the server like...

KendoUI Grid - Complex JSON with inconsistent keys

javascript,json,kendo-ui,kendo-grid

You can use column templates: columns: [ { field: "id", title: "User Id" }, { field: "name", title: "User Name", }, { field: "type", title: "User Type", template: function(dataItem) { return dataItem.type ? kendo.htmlEncode(dataItem.type) : ""; } }, { field: "address", title: "Street 1", template: function(dataItem) { return dataItem.address.street1 ?...

check if file is image

c#,asp.net,asp.net-mvc

You can't do this: string.Contains(string array) Instead you have to rewrite that line of code to this: if (file == null || formats.Any(f => file.Contains(f))) And this can be shortened down to: if (file == null || formats.Any(file.Contains)) ...

Codeigniter Select JSON, Insert JSON

json,codeigniter,select,insert,routing

You want to return json object in response, so it's required to set json type in response header. As given here public function select(){ $data['query'] = $this->users->select(); $this->output ->set_content_type('application/json') ->set_output(json_encode($data['query'])); } It is required to encode part as below for insert part. so you can use this generated url to...

System.net.http.formatting causing issues with Newtonsoft.json

c#,asp.net,asp.net-mvc,json.net

Does the assemblyBinding tag have proper xmlns schema? Check if the issue you are encountering is same as Assembly binding redirect does not work

onSuccess and onFailure doesn't get fired

javascript,c#,asp.net,webmethod,pagemethods

You PageMethod is looking like this PageMethods.LoginUser(onSuccess, onFailure, email, pass); And when you call it, it looks like this PageMethods.LoginUser(email, pass); Your arguments should be in the same order as the method. PageMethods.LoginUser(email, pass, onSuccess, onFailure); ...

String comparison in AngularJS

javascript,json,angularjs,ionic-framework,string-comparison

You are iterating over wrong node:) for(var i=0;i<$rootScope.items.length;i++) { alert("Inside for loop"); if (name === $rootScope.items[i].names) // you iterate over items, not names, which it an Json property inside item { alert("If condition satisfied"); } } ...

Create n:m objects using json and sequelize?

javascript,json,node.js,sequelize.js

Have a look at nested creation (the feature is not documented yet) Store.create({ name:'corner store', address: '123 Main Street', products: [ { name: 'string beans' }, { name: 'coffee' }, { name: 'milk' } ] }, { include: [Product] }); This will create both stores and products and associate the...

JQuery mutiple post in the same time

javascript,php,jquery,json

You can use the jQuery when function (https://api.jquery.com/jquery.when/) to wait for all three promises to resolve. You only need to make sure you also return the promise in your nb1, nb2, nb3 functions. function nb1() { return $.post("p1.php", { action: 1 }, function(data) { console.log(data); }, "json") .fail(function(data) { console.log("error");...

Deserializing Json data to c# for use in GridView - Error Data source is an invalid type

c#,json,gridview,serialization,.net-4.5

You're binding the container object, not the list itself. Change it to: GridView1.DataSource = personDetail.PersonDetails; And it should work....

Gridview items not populating correctly

asp.net,vb.net

Try this vb code behind, then comment out my test Private Sub BindGrid() Dim dt_SQL_Results As New DataTable '' Commenting out to use test data as I have no access to your database 'Dim da As SqlClient.SqlDataAdapter 'Dim strSQL2 As String 'Dim Response As String = "" 'strSQL2 = "SELECT...

access the json encoded object returned by php in jquery

php,jquery,ajax,json

Try: $.ajax({ url: "functions.php", dataType: "JSON", data: {id: id}, type: 'POST', success: function(json){ for(var i=0;i<json.length;i++){ alert(json[i].fname); } } }); ...

Parse JSON output from AlamoFire

json,swift,nsurlrequest

If I believe the println of aStatus, the property title is a String, not a Dictionary. Change this part in your code (cast as String instead of as NSDictionary): if let user = aStatus["title"] as? String { println( "TITLE \(user)") } ...

Sorting in Ruby on rails

ruby-on-rails,json,sorting

You're not getting the results you want because you're not assigning the sorted user_infos back into the user_infos variable. You can do the following: user_infos = user_infos.sort {|a, b| - (a['can_go'] <=> b['can_go']) } # -or- user_infos.sort! {|a, b| - (a['can_go'] <=> b['can_go']) } The first version of sort creates...

Deserializing JSON into c# class

c#,json,couchdb

You could create a custom JsonConverter for this: [JsonConverter(typeof(ClickConverter))] public class Click { public DateTime Date { get; set; } public string Code { get; set; } public string Url { get; set; } public int Count { get; set; } } public class ClickConverter : JsonConverter { public override...

How to rearrange CSV / JSON keys columns? (Javascript)

javascript,json,csv,papaparse

Papa Parse allows to specify order of fields in the unparse() function: var csv = Papa.unparse({ fields: ["ID", "OrderNumber", "OrderStatus", "StartTime", "FinishTime", "canOp", "OpDesc", "UOM"], data: [{ OrderStatus: "Good", canOp: "True", OpDesc: "Good to go", ID: "100", OrderNumber: "1000101", FinishTime: "20:50", UOM: "K", StartTime: "18:10" }, // ... ] });...

Uncaught error: Invalid type for google table column

javascript,json,google-maps,google-visualization

You should change your row data.addColumn('String', 'sitecode'); to data.addColumn('string', 'sitecode'); (non capital "s" in "string"), of course this applies to all of your added columns. Javascript is case-sensitive....

Fatal error catched by register_shutdown_function and update json_encode

php,json,fatal-error

Why move one array to another array and then echo the second array. Why not just do this function shutdown(){ $error = error_get_last(); echo json_encode($error); } Or even this function shutdown(){ echo json_encode(error_get_last()); } Apart form the use of an unnecessary array, this will give you all the information available...

php array returns undefined but print_r shows otherwise [duplicate]

php,arrays,json,undefined

The array you're looping looks like this: Array ( [0] => Array ( [mstatus] => 1 [mhearingnum] => first [mminutes] => adakjaflafjlarjkelfkalfkd;la ) [1] => Array ( [mhearingnum] => second [mminutes] => ) [2] => Array ( [mhearingnum] => third [mminutes] => ) ) Only the sub array at the...

Retrieve data from one table and insert into another table

sql,asp.net,sql-server

INSERT INTO tbl2 ( Name ,parentId ) SELECT DISTINCT manager ,0 FROM tbl1 WHERE manager NOT IN ( SELECT employee FROM tbl1 ) INSERT INTO tbl2 SELECT DISTINCT employee ,0 FROM tbl1 UPDATE tbl2 SET parentid = parent.id FROM tbl2 INNER JOIN tbl1 ON tbl2.Name = tbl1.employee INNER JOIN tbl2...

Why i get can not resolve method error in class android?

android,json

You didn't create setName() method in Person class. public class Person { private String name; private String country; private String twitter; //getters & setters.... public void setName(String pName) { this.name = pName; } public void getName() { return this.name; } } ...

Can't save json data to variable (or cache) with angularjs $http.get

json,angularjs,web-services,rest

$http.get is asynchronous. When cache.get or return result are executed, HTTP request has not completed yet. How are you going to use that data? Display in UI? E.g. try the following: // Some View <div>{{myData}}</div> // Controller app.controller('MyController', function ($scope) { $http.get('yoururl').success(function (data) { $scope.myData = data; }); }); You...

convert from json to array

javascript,php,json

First off, your associative array is flipped. You need to change array($wholeNumber['DocumentNbr'] => 'Number', $wholeNumber['DocumentRevision'] => 'Revision'); to array('Number' => $wholeNumber['DocumentNbr'], 'Revision' => $wholeNumber['DocumentRevision']); You need that in order to access the elements of the JSON. Then, in your loop, you would use wholeNumberData[i].Number to get the number and wholeNumberData[i].Revision...

How do ASP.NET Web APIs work once built with MSBUILD?

c#,asp.net,msbuild

The WebApi is a web project and on compiling it creates a dll. It is not a class library or a nuget package to consume and use it. I have practically implemented this in a real world application and below are my thoughts for your understanding. Your question is Once...

Can I uniquely identify 2 check boxes so that I can add a different image to each?

html,css,asp.net,checkbox

Here is an example of what I meant: (Oh and, forgive the images please :) ) #field1,#field2{ display:none; } #field1 + label { padding:40px; padding-left:100px; background:url(http://www.clker.com/cliparts/M/F/B/9/z/O/nxt-checkbox-unchecked-md.png) no-repeat left center; background-size: 80px 80px; } #field1:checked + label { background:url(http://www.clker.com/cliparts/B/2/v/i/n/T/tick-check-box-md.png) no-repeat left center; background-size: 80px 80px; } #field2 + label { padding:40px;...

Nested JSON structure to build side-by-side d3.js charts

javascript,json,d3.js

No, you don't need to use .nest here. The easiest way to build the required data structure is as you suggest (d3 always wants an array to iterate over): var nestedData = [ years[0].chartOne, years[0].chartTwo ]; After that, it's as simple as cleaning up the accessor functions for your data...

Insert data in collection at Meteor's startup

javascript,json,meteor,data,startup

Ok, you'll want to check out Structuring your application. You'll have to make the file with the definition load earlier, or the one with the fixture later. Normally you have your collections inside lib/ and your fixtures inside server/fixtures.js. So if you put your insert code into server/fixtures.js it'll work....

why i don't get return value javascript

javascript,jquery,html,json,html5

the first "A" in AJAX stands for "Asynchronous" that means, it is not executed right after it has been called. So you never get the value. Maybe you could first, get the os list and then output what you need, like this: function createCheckBoxPlatform(myDatas) { $.ajax({ url: "/QRCNew/GetOS", type: "post",...

Difference between application and module pipelines in Nancy?

c#,asp.net,nancy

The module- and application pipelines are explained in detail in the wiki. It's basically hooks which are executed before and after route execution on a global (application pipelines) and per-module basis. Here's an example: If a route is resolved to a module called FooModule, the pipelines will be invoked as...

How to make a website work only with https [duplicate]

asp.net,ssl,https

Sure, assuming you are using IIS to host your site, open IIS Manager and select your web site and then binding on the right: make sure you only have a binding for https not for http. This way IIS will only send https traffic to that web site. Edit: What...

Serializing a java bean into a cookie: Is it bad?

java,json,cookies

I guess the answer depends on your answer to these questions: Since you can never trust ANYTHING that comes in a client request, are there any harmful effects that could come by a hacker spoofing the pojo value? By sending the object to the client, does this expose any internal...

Call function on Server from iOS app - Objective C

ios,objective-c,json,server,backend

You just need to POST data to your server. Port could be anything you want, should be 80. Host your script with a domain url so that you can make network request publicly. You can try this function: -(NSData *)post:(NSString *)postString url:(NSString*)urlString{ //Response data object NSData *returnData = [[NSData alloc]init];...

Response 200 OK but Jquery shows error?

javascript,jquery,json

The code you've supplied, by itself, works fine. It breaks if you try to force the use of JSONP because the server you are making the request to doesn't support that. It does support CORS (which is the modern replacement for JSONP), and you don't need to do anything special...

Convert Double from String

asp.net,vb.net,visual-studio-2012,converter

The result isn't wrong, it only has lower precision than you expected. Floating point numbers have a limited precision by design, and you simply can't expect to get a result that is more precise than its limit. You can use a Decimal to get higher precision. In this case it...

deployment of a site asp.net and iis

c#,asp.net,iis

There are several domain providers like: godaddy, name etc you can use to buy a domain name. These providers also provide you steps to map the domain name to your website. Check out this link for example. This link explains domain name configuration in details.

Catch concurrency exception in EF6 to change message to be more user friendly

c#,asp.net,.net,entity-framework,entity-framework-6

You are executing an asynchronous method. This means that any exceptions will be thrown when you call await on the returned task or when you try to retrieve the results using await myTask; You never do so, which means that the exception is thrown and caught higher up your call...

Access manager information from Active Directory

c#,asp.net,active-directory

try this: var loginName = @"loginNameOfInterestedUser"; var ldap = new DirectoryEntry("LDAP://domain.something.com"); var search = new DirectorySearcher(ldap) { Filter = "(&(objectCategory=person)(objectClass=user)(sAMAccountName=" + loginName + "))" }; var result = search.FindOne(); if (result == null) return; var fullQuery = result.Path; var user = new DirectoryEntry(fullQuery); DirectoryEntry manager; if (user.Properties.PropertyNames.OfType<string>().Contains("manager")) { var managerPath...