Get body of request in ASP.NET Web Api - c#

I faced problem like this.
I have method in controller, that receive data in body of POST request.
Here is method.
// POST: api/StartWorkingDays
[ResponseType(typeof(StartWorkingDay))]
public IHttpActionResult PostStartWorkingDay(StartWorkingDay startWorkingDay)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.StartWorkingDays.Add(startWorkingDay);
db.SaveChanges();
return Json(new { Result = "Success", Message = "Saved Successfully"});
//return CreatedAtRoute("DefaultApi", new { id = startWorkingDay.Id }, startWorkingDay);
}
How I can see body of request that I receive?
Thank's for help.

[HttpPost]
public HttpResponseMessage PostStartWorkingDay([FromBody] StartWorkingDay startWorkingDay)
{
//here above startWorkingDay is body your mobile developer will send
//you and data can be viewed while debugging ,
//tell mobile developer to set content-type header should be JSON.
return Request.CreateResponse(HttpStatusCode.Created, "Success");
}
Why your return type is Json ? you should use HttpResponse . I believe you are using Web api 2 . With Attribute routing and if you want to send response in json format then remove Xml formatter from WebApiConfig.cs file inside App_Start folder

Related

Upload files Asp.NET MVC 4 - Web API - Http Put verb/method

So I have to make a method in asp.net for an API that accepts 2 files via PUT (1 json and 1 xml for processing data, not saving- because I have to, OK? :) ), sending the request via fiddler..
Right now I'm sending the request like this on fiddler (PUT METHOD):
Content-Type: multipart/form-data
Authorization: XXXXX
Host: XXXX
Request body:
<#INCLUDE *C:\Users\ZZZZ.json*#>
<#INCLUDE *C:\Users\XXXX.xml*#>
Here's what I've tried inside the controller so far:
[HttpPut, Route("api/Student/{studentId}/Classes/{classId}")]
public async Task<string> Put(int studentId, int classId)
{
var file = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files[0] : null;
Stream fileContent = await this.Request.Content.ReadAsStreamAsync();
MediaTypeHeaderValue contentTypeHeader = this.Request.Content.Headers.ContentType;
if (fileContent != null)
return "ok";
return "not ok";
}
So far the file is not being uploaded nor appears within the request (everything's null). I've also tried the "Request" variable and HttpContext.
Tried the exact same thing but with a POST Method (including the boundaries) and the same happens.
What would you do in order to make this work? I really have to send a json object and another in xml, I really can't change languages or send everything in json ('cause that I could make it work)...
PS: The files don't have a defined structure, it has to be dynamic
PS2 : How would you then attempt to read those files without actually saving them?
You don't have to use a stream to read the file content. You can just try using the HttpPostedFile.
[HttpPut, Route("api/student/{studentId}/classes/{classId}")]
public async Task<string> Put(int studentId, int classId)
{
if (HttpContext.Current.Request.Files.Count == 0)
throw new HttpResponseException(new HttpResponseMessage()
{
ReasonPhrase = "Files are required",
StatusCode = HttpStatusCode.BadRequest
});
foreach (string file in HttpContext.Current.Request.Files)
{
var postedFile = HttpContext.Current.Request.Files[file];
if (!(postedFile.ContentType == "application/json" || postedFile.ContentType == "application/xml"))
{
throw new System.Web.Http.HttpResponseException(new HttpResponseMessage()
{
ReasonPhrase = "Wrong content type",
StatusCode = HttpStatusCode.BadRequest
});
}
}
return "OK";
}
POSTMAN
My POSTMAN:
enter image description here
Fiddler

How to return response JSON data with status code?

When I used MVC controllers I used "return OK(object);" or "return BadRequest(ErrorMessage)" and such.
How can I achieve this is Razor Pages?
I tried return new JsonResult(object); which works when the status code can be 200.
But what if I want to return status code 400 with a JSON error message.
You can return a JsonResult from a Razor Page handler method, and set the HTTP status code for the response:
public IActionResult OnGet()
{
Response.StatusCode = 400;
return new JsonResult(new { message = "Error" } );
}

c# webapi post() and post([FromBody])

I'm building an webapi in c# to be called by an outside server.
let's say my API address is www.server.com/webapi/service1
when I set the address above in the app that will use it, it sends a simple POST with an empty body to service1 and waits for a specific KEY as response (in body), like an authentication. ok.
the same service1 can be called, using POST too, passing a raw JSON in the body, and I'm using the [FromBody] attribute to get the body and process.
I tried this to manage the empty POST call and the call with body data:
[HttpPost]
[Route("webapi/service1")]
public HttpResponseMessage Post()
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(TokenKey.ToString(), System.Text.Encoding.UTF8, "text/html");
return resp;
}
[HttpPost]
[Route("webapi/service1")]
public async Task<HttpResponseMessage> Post([FromBody] RetornoChat retornoChat)
{
await closedChat(retornoChat); //process body
return resp;
}
but it was not working.I manage a workaround like the code below, I check if the class in [FromBody] is empty, if this is the case return the special string to validate and finish, if there is a body then get the data validate and process. I'm wondering if there is a better solution.
I really thought that the solution was to double the post method and when there was a body it would call the post with the [frombody] and when there is no body it would go to the empty post.
[HttpPost]
[Route("webapi/service1")]
public async Task<HttpResponseMessage> Post([FromBody] RetornoChat retornoChat)
{
var resp = new HttpResponseMessage(HttpStatusCode.OK);
resp.Content = new StringContent(TokenKey.ToString(), System.Text.Encoding.UTF8, "text/html");
if (retornoChat == null)
{
}
else
{
//get the body data and process
}
return resp;
}
Thanks in advance for your time!

asp.net webapi 2.0 handle wrong route

I have developed an API for an application and i have all routes set up, but when the users request the wrong action, the server returns 404 by default and i tried to find some way of changing that but i didnt find anything...
So lets say i have an api with the following route:
/api/school/1/classes
if the client requests
/api/school/1/classez
i want to return response code 501 or 405 instead of the default 404.
how can this be done?
Use Route attributes.
[HttpGet]
[Route("api/{id}/foo")]
public HttpResponseMessage foo(int id)
{
var response = new ApiResponse();
response.StatusCode = HttpStatusCode.OK;
return response;
}
[HttpGet]
[Route("api/{id}/{route}")]
public HttpResponseMessage bar(int id)
{
var response = new ApiResponse();
response.StatusCode = HttpStatusCode.BadRequest;
return response;
}
If they type it correctly then it will enter foo. Otherwise they will enter bar and you can handle that how ever you like.

should web api content negotiation from xml to json insert #?

I have an xml document that I want to return via a web api call.
I want to allow the user the option of the response via content negotiation.
[HttpGet]
public HttpResponseMessage Get()
{
var doc = new XmlDocument();
doc.LoadXml("<MyExport SomeProperty='Some Value'></MyExport>");
return Request.CreateResponse(HttpStatusCode.OK, doc);
}
When I request this an Accept header of application/json I get:
{
"MyExport": {
"#SomeProperty": "Some Value"
}
}
Is it correct that # is included in the property name?
If so why?

Categories

Resources