I am new to Web API and trying learn how to debug Web API with POSTMAN.It is working with GET request only POST request has some trouble. I am not able to trouble shoot what exactly the error is.
[HttpPost]
public HttpResponseMessage StudentDetails(Student data)
{
return new HttpResponseMessage()
{
Content = new StringContent(JArray.FromObject(data).ToString(), Encoding.UTF8, "application/json")
};
}
And Student Class is as below.
public class Student
{
public int StudentId { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string SSN { get; set; }
public string PersonalEmail { get; set; }
}
And I am trying to test the above action in POSTMAN. I added Content-Type as "application-json" and passing JSON as below .
{
StudentId :1
FirstName : 'SINI' ,
LastName :'A',
SSN : '7894300',
PersonalEmail: 'sini#gmail.com'
}
And In the POSTMAN, I gave the below URL :
http://localhost:60893/WebAPIDemo/api/Student
But it is giving me "The resource cannot be found".
Everything was perfect. I had two projects, one is web API and the other one is MVC. I forgot to keep web API as start up project.
url is not correct, change it to:
http://localhost:60893/WebAPIDemo/api/StudentDetails
Related
I'm trying to add company with multiple employees with their picture.
But I'm facing an issue while posting request, not worrying about internal logic.
There are 2 tables Company & Employee and I want to add company with multiple employees and their picture in a single post request, but I'm getting like this in Swagger:
Instead I want array of this... want this block multiple times:
Please, tell me how can I implement it to get the result I want?
Controller
[HttpPost]
public async Task<ActionResult<Unit>> CreateCompany([FromForm] CreateCompanyRequestViewModel Company)
{
//
}
EmployeeRequestViewModel
public class EmployeeRequestViewModel
{
public string EmployeeName { get; set; };
public IFormFile ProfileImage { get; set; };
}
CompanyViewModel
public class CreateCompanyRequestViewModel
{
public string CompanyName { get; set; };
public IFormFile CompanyLogo { get; set; };
public List<EmployeeRequestViewModel> Employees { get; set; };
}
You could try with postman as below:
Result:
I'm trying to receive data from an external API that's doing an HTTP POST against my Web API. The content-type of this request is: application/x-www-form-urlencoded. I want the content from this POST request to be saved into my SQL database using Entity Framework. The request is succesful and giving status code 200 but all the values stored into the database are NULL. So I'm wondering how I can map the values from the raw post request to my alerts model.
I have included a screenshot from the POST request using webhook.site below.
AlertsAPI
[HttpPost]
[Consumes("application/x-www-form-urlencoded")]
public async Task<IActionResult> PostAlert([FromForm] Alerts alert)
{
db.Alerts.Add(alert);
await db.SaveChangesAsync();
return CreatedAtAction("Get", new { id = alert.id }, alert);
}
Alerts.cs
public class Alerts
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
[FromForm(Name = "sensor")]
public string sensor { get; set; }
[FromForm(Name = "probe")]
public string probe { get; set; }
[FromForm(Name = "group")]
public string group { get; set; }
[FromForm(Name = "device")]
public string device { get; set; }
}
This is the content that im trying to map to my Alert.cs model and save into my database using Entity Framework.
Raw content
Date%2FTime%3A%2005%2F12%2F2020%2020%3A54%3A28%0D%0A%0D%0ATime%20zone%3A%20W.%20Europe%20Standard%20Time%0D%0A%0D%0A=%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%0D%0A%0D%0ASensor%3A%20Ping%20%28Ping%29%0D%0A%0D%0APriority%3A%20*****%0D%0A%0D%0A%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%3D%0D%0A%0D%0AProbe%3A%20Local%20Probe%0D%0A%0D%0AGroup%3A%20Linux%20%2F%20macOS%20%2F%20Unix%0D%0A%0D%0ADevice%3A%127.0.0.1
I have a model like this.
public class ClientDto
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
public string Address { get; set; }
public IFormFile ProfilePicture { get; set; }
}
And API controller like this:
[HttpPost]
public async Task<OperationResult> Post([FromForm] ClientDto c)
{
ImageHandler handler = new ImageHandler(env);
Client client = new Client()
{
Address = c.Address,
FirstName = c.FirstName,
LastName = c.LastName,
PhoneNumber = c.PhoneNumber,
PhotoPath = await handler.UploadFile(c.ProfilePicture)
};
return await clientRepository.AddClient(client);
}
Now if I make a Post request with postman after including a file with ProfilePicture as key (under Postman >> Body >> form-data section), model binding works as expected. The api controller receives PofilePicture and rest of the properties null. But if I include json string for other properties like this (under Postman >> Body >> raw section)
{
"c":{
"FirstName": "XYZ",
"LastName":"ABX"
}
}
OR
{
"FirstName": "XYZ",
"LastName":"ABX"
}
model binding no longer works. How do I hit the api controller with postman if i want to provide all properties?
You're mixing data sent to the controller - it's confused.
In your request with the image the content type is multipart/form-data as the body contains a file and potentially other form data fields. In the request with JSON the content type is application/json and you're not sending any file data.
You have to decide to either only send the JSON or the form data.
In this case, since you're sending a file, you need to use multipart/form-data and just set the missing fields in the form fields from Postman (see how to set Postman form-data parameters here).
I'm running server build with asp.net core (v2.1) web api and have this REST HTTP call:
POST http://website.com/callback
with the headers:
...
Content-Type: application/x-www-form-urlencoded
and the body:
response%5Bkey%5D=123&response%5Bname%5D=hi
I want to receive this message at this point:
[HttpPost]
[Route("callbacks")]
public ActionResult Hook([FromForm]Model model)
{
// <---- Model has instance but empty fields
return Ok();
}
My Model is:
public class Model
{
public string key { get; set; }
public string name { get; set; }
}
Somehow the brackets ("[key]" and "[name]") are not being parsed into my model instance. They are null both, although I provide them in body.
How to solve it?
You should set name in form for your properties:
public class Model
{
[FromForm(Name = "response[key]")]
public string key { get; set; }
[FromForm(Name = "response[name]")]
public string name { get; set; }
}
I am using Microsoft Web API 2 and Protobuf-net to serialize my data. Everything is working perfectly, except when I want to send binary data to the Web API controller. I end up getting a 500 error.
Is this currently possible or is this restricted to serialization only? To verify my response was correct, I used ProtobufJS and it decoded it correctly. To pinpoint my issue, I excluded it and directly sent my response as soon as I got it. Any help getting set up would be greatly appreciated.
Web API Controller
public class UserController : ApiController
{
// GET api/<controller>
public User Get()
{
var user = new User{ Id = "ABC1", FirstName = "John", LastName = "Doe" };
return user;
}
// GET api/user/
public void Post(User user)
{
var type = "POST";
}
}
Model
[ProtoContract]
public class User
{
[ProtoMember(1)]
public string Id { get; set; }
[ProtoMember(2)]
public string FirstName { get; set; }
[ProtoMember(3)]
public string LastName { get; set; }
}
Javascript
<script>
var get = new XMLHttpRequest();
get.open("GET", "api/user", true);
get.responseType = "arraybuffer";
get.setRequestHeader("Accept", "application/x-protobuf");
get.onload = function (event) {
var arrayBuffer = get.response;
var post = new XMLHttpRequest();
post.open("POST", "api/user", true);
post.setRequestHeader("Accept", "application/x-protobuf");
post.overrideMimeType("application/x-protobuf");
post.send(arrayBuffer);
}
get.send(null);
</script>