C# consume Angular 4 class - c#

hou would i consume the following request in my C# web Api.
Here is my Request:
this._http.post(
this.url + 'api/Test',
{ auth: this.authClass},
{ headers: this.header }
).map(
(res) => res.json()
).subscribe(
(res) => {
console.log("VALUE RECEIVED: ", res);
})
Here is my AuthClass:
export class Auth{
username:string = "";
password:string = "";
}
I have the same class in c# and need to know how do i go about receiving the class as a whole in c#.
I tried:
[HttpPost]
public IHttpActionResult login(HttpRequestMessage request)
{
var jsonString = await request.Content.ReadAsStringAsync();
var model = JsonConvert.DeserializeObject<auth>(jsonString);
return Ok();
}
My problem is that it can't parse the json to auth. My json string getting send currently looks like this.
{
"auth": {
"username": "admin",
"password": "admin1"
}
}
If its just
{
"username": "admin",
"password": "admin1"
}
then it works without any problems. But i need it to consume the first json example

about receiving the class as a whole in c#.
You wouldn't get the class. The recommended wire transfer is JSON and it will just give you the Object properties.
More
Lookup JSON serialization. The internet is full of examples with C# + AngularJS.

Arno,
You should receive a json object in your web api method.
Then use Json.Net to convert your json object to the C# object you desire.
Hope it helps.

So the answer was to wrap the auth class inside another class.
public class authReq
{
public auth request { get; set; }
}
public class auth
{
public string username { get; set; }
public string password { get; set; }
}
And then i deserialize the authReq like so.
var model = JsonConvert.DeserializeObject<register>(jsonString);

Related

can we pass array to post request in react using axios?

let assume,
companyDetail is an object, and I have to pass list of company details to API.
so can I d sent array of object in post request like this:-
axios.post("",);
note API is made in ASP.NET Core Web API.
what type of data can we send ?
You can send an array of objects as long as the endpoint expect to receive this type of data.
With axios:
const companyDetails = [
{ ... },
{ ... },
{ ... },
];
axios.post("https://myapi.com/companydetails", companyDetails)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
Yes you can pass data as array of object companyDetail but its depends on how API request body is created in backend. If API wants request body in some other custom variable lets as reqBody the you have to assign your companyDetail to reqBody
axios.post("endpoint", {reqBody: companyDetail})
If API wants request body in companyDetail itself then:
axios.post("endpoint", {companyDetail})
CompanyDetail is an object, and I have to pass list of company details
to API. so can I d sent array of object in post request like this:-
axios.post("",);Note API is made in ASP.NET Core Web API. What type of
data can we send ?
Well, to begin with your first concern, yes we definitely can post list of object as axios.post("",) fashion. Considering your scenario we can write that snippet as following:
Let's assume, we have model as below:
Model:
public class CompanyDetails
{
public int CompanyId { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
Asp.net core Web API:
[Route("api/[controller]")]
[ApiController]
public class AxiosWebApiController : ControllerBase
{
[HttpPost]
[Route("CompanyDetails")]
public async Task<IActionResult> CompanyDetails(List<CompanyDetails> companyDetails)
{
// Do whatever you like here
return Ok(companyDetails);
}
}
What type of data can we send ?
Well, its up to you, if your controller accept list of object as Model just like this List<CompanyDetails> companyDetails then you can do as following.
Axios Request:
#section Scripts
{
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
const CompanyId = "CompnayId:";
const Name = "Name:";
const Email = "Email:";
const companyDetails = [];
for (let i = 1; i <= 10; i++) {
const companyObject = {
CompanyId: CompanyId + i,
Name: Name + i,
Email: Email + i
}
companyDetails.push(companyObject);
}
console.log(companyDetails);
axios.post("http://localhost:5094/api/AxiosWebApi/CompanyDetails", companyDetails);
</script>
}
Note: If your controller accept [FromForm] then append as FormData() just like formData.append("CompanyId", 1); then push to your array object.
In addition, please check your browser console if the object posted accordingly as following:
Output:

Deserializing the JSON object passed from Ajax to ASP.NET MVC

I'm trying to send the JSON object through Ajax request to ASP.NET MVC. While getting the JSON object in the backend, it receives the object in string format as shown below.
How to deserialize it into a C# object?
C# ASP.NET MVC code:
public string GetLists(string list1)
{
return JsonConvert.SerializeObject(list1, JsonSetting);
}
JavaScript code:
button.onclick=()=> {
let xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.response)
}
}
let list1=[
{"id":"1a","level":1},
{"id":"2b","level":14},
{"id":"3c","level":23}
]
var params ="list1=" + JSON.stringify(list1)
xhr.open("POST", "/Status/GetLists");
xhr.setRequestHeader('content-type', "application/x-www-form-urlencoded");
xhr.send(params);
}
Output:
[
{\"id\":\"1a\",\"level\":1},
{\"id\":\"2b\",\"level\":14},
{\"id\":\"3c\",\"level\":23}
]
You can use System.Text.Json.JsonSerializer
but you should include a type for deserialization so that c# knows the kind of data you are trying to receive.
In your code, you only give back the string but not a c# object so you have to specify a class or an interface to model your data.
Example snippet for receiving the data:
using System;
using System.Collections.Generic;
using System.Text.Json;
// define the structure of the object you want to recieve
interface MyDataStructure
{
public string id { get; set; }
public int level { get; set; }
}
class Program
{
public void ReadData(string jsonData)
{
// Creating a list of objects from your type. The Json Serializer is flexible and also workes when using Arrays
List<MyDataStructure> data = JsonSerializer.Deserialize<List<MyDataStructure>>(jsonData);
foreach (var obj in data){
Console.WriteLine($"{obj.id}||{obj.level}");
}
}
}
I recommend you should check out the docs on deserialization and serialization.
An alternative to the .Net JsonSerializer is Newtonsofts Json.NET
your data is serialized twice, at first you serialize it manually , after this net serialized it automaticaly to send data back. So you don't need to serialize it at all, net will do it for you. Change your action to this
public ActionResult<List<Item>> GetLists([FromBody] List<item> list)
{
return Ok(list);
}
class
public class Item
{
public string id { get; set; }
public string level { get; set; }
}
and ajax
var params =JSON.stringify(list1);
xhr.open("POST", "/Status/GetLists");
xhr.setRequestHeader('content-type', "application/json");
xhr.send(params);
You are trying to send a json object with a wrong content-type, in your case the content-type should be application/json and you don't have to add "params" + JSON.stringify(list1) as this will be sent in the request body, you should send just the list1 variable.
xhr.setRequestHeader('content-type', "application/json");
xhr.send(JSON.stringify(list1));
Then you will be able to deserialize the object in your backend endpoint like:
public class Item
{
public string id { get; set; }
public string level { get; set; }
}
[HttpPost]
public List<Item> GetLists([FromBody] object value)
{
var items = JsonConvert.DeserializeObject<List<Item>>(value.ToString());
return items;
}

How do I receive data in my HttpPost in C# as a custom class?

How do I receive the data coming from the post (.../api/search) as a custom c# object?
Do I receive as a JSON string, deserialize it, then cast to my object? How do I do that?
Or do I receive it immediately as a SearchObject? How would I do that?
Right now my POST request is returning a blank object "{}".
namespace Safety.Api
{
[RoutePrefix("api")]
public class SearchController : ApiController
{
[Route("search")]
[HttpPost]
public string TestSearch([FromBody] SearchObject mystring)
{
return JsonConvert.SerializeObject(mystring);
}
}
}
This is my custom class:
public class SearchObject
{
string distributionType,
distributionTemplate,
productLine,
studyOfOccurrence,
countryOfOccurrence;
}
WebApi will automatically deserialize JSON to the parameter type of the action. You can also return complex objects and WebApi will serialize these to JSON before they are sent.
So if your action looks like this
[Route("search")]
[HttpPost]
public SearchObject TestSearch([FromBody] SearchObject yourSearchObject)
{
return yourSearchObject;
}
And you perform a javascript fetch request like this
fetch('/api/search', {
method: 'POST',
data: JSON.stringify({
distributionType: 'some type',
distributionTemplate: 'a template',
productLine: 'the product line',
studyOfOccurence: 'the study',
countyOfOccurence: 'a country'
}),
headers: {
'content-type': 'application/json'
}
})
.then(res => res.json())
.then(data => console.log(data))
The console.log(data) statement should output
{
distributionType: 'some type',
distributionTemplate: 'a template',
productLine: 'the product line',
studyOfOccurence: 'the study',
countyOfOccurence: 'a country'
}
I've had trouble in the past where WebApi will try to return XML instead of JSON, or it will try to parse the data from the request as XML instead of JSON. By setting the content type header to application/json, you're telling WebApi to parse the data as JSON. You can allso set the 'accepts' header to application/json if you find that the action is returning the data as XML
You need to declare the values on your class as properties e.g.:
public class SearchObject
{
public string DistributionType { get; set; }
public string DistributionTemplate { get; set; }
public string ProductLine { get; set; }
public string StudyOfOccurrence { get; set; }
public string CountryOfOccurrence { get; set; }
}
The middleware in ASP.NET will automatically convert the object in the body to your class (if it can). It looks for a set method on each class member to do this. As your class only had variables then the middleware was unable to find a matching property and, as you saw, it did not populate the object.
The method should now return the correct values as a serialized JSON object.

.NET core web api Taking JSON input and returning it results in NULL output

I am writing a web API that takes any JSON input, wraps it in an envelope (basically adding an ID) and then returns it, but I am having issues that the incoming JSON always seems to be NULL even though I am sending in valid JSON using postman
the simple controller is as follows
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace NWCloudTransactionHost.Controllers
{
[Route("api/[controller]")]
public class TransactionInput : Controller
{
[HttpPost]
public IActionResult Index([FromBody] OriginalTransaction originalTransaction)
{
var transactionEnvelope = new TransactionEnvelope { Id = Guid.NewGuid(), OriginalTransactionData = originalTransaction };
return Json(transactionEnvelope);
}
}
public class OriginalTransaction
{
public string OriginalTransactionData { get; set; }
}
public class TransactionEnvelope
{
public Guid Id { get; set; }
public OriginalTransaction OriginalTransactionData { get; set; }
}
}
Use a stream reader to read the body content stream. Then return a content result with contentType: "application/json".
[HttpPost]
public ContentResult Index()
{
using (var reader = new StreamReader(Request.Body, Encoding.UTF8))
{
// Get the body (json) as a raw string
var originalTransaction = reader.ReadToEnd();
// Wrap the transaction
var id = Guid.NewGuid();
var envelope = $"{{ \"Id\": \"{id}\", \"OriginalTransactionData\": {originalTransaction} }}";
// return json
return Content(envelope, "application/json", Encoding.UTF8);
}
}
Be aware that in this example there is no validation on the json. If it's incorrect (eg. missing a comma somewhere etc.), the answer won't be valid too. I recommed you the check if the raw string originalTransaction is valid json before wrapping it in the envelope.
Sample
Request
{ "Test": "Hello World" }
Response
{
"Id": "a9258e99-86cf-4f1d-9e17-0df7ba1dce5e",
"OriginalTransactionData": {
"Test": "Hello World"
}
}
Edit
I messed up a bit with my quick answer. Here's the revised version. I changed how to read the request json and how to send the response json back. This version should work now. Also fixed the invalid string interpolation and put the id in escaped quotes. Added a sample which worked for me.
Despite the stream reader I think it's more straight forward now.

OWIN ApiController access to the request body/stringified JSON

This is in OWIN & .Net 4.5.2
Using debug I'm proving this controller's method is being called by the web request.
My thing is the request body contains a JSON stringified object:
"{ 'id':'12', 'text1':'hello', 'test2':'world' }"
Which is applicably encoded as it is transferred on the line.
I've tried so many things I'm so confused now.
How do I get the decoded string so I can JSON.Parse() that or better yet get .Net to just given me an object?
In one version (long ago now) I had a defined type for this object. If I need that great, not a high challenge. But if I only have the JSON object from the string that's fine too.
public class cController : ApiController {
[HttpPut]
public string put(string id) {
var bdy = this.Request.Content;
//Console.WriteLine("PUT containers {0}", body);
return string.Empty;
}
}
In case it helps, the bdy.ContentReadStream is null. I don't know if this is good, bad, or important. Maybe Request.Content isn't the way to go but seems to me like if I'm going to read the body as a stream then it shouldn't be null.
I also tried working through System.Web.HttpContext. If that is somehow the answer I have no problem going back to that. But I couldn't find the secret sauce.
Pass the desired model as a parameter to the action and the frame work should be able to parse it provided it is valid JSON
public class cController : ApiController {
[HttpPut]
public IHttpActionResult Put(string id,[FromBody] Model body) {
if(ModelState.IsValue) {
return Ok(body.text1);
}
return BadRequest();
}
}
Where Model is defined as
public class Model {
public string id { get; set; }
public string text1 { get; set; }
public string test2 { get; set; }
}

Categories

Resources