I've got a .NET Core application that has a controller named Documents with a POST signature like this:
[HttpPost]
public async Task<IActionResult> PostAsync(CreateDocumentRequest createDocumentRequest)
The CreateDocumentRequest looks like this:
public class CreateDocumentRequest
{
public string Name { get; set; }
public string Description { get; set; }
public IFormFile File { get; set; }
}
Pretty simple. I then have a POST request configured in Postman like this:
URL: http://localhost:9090/api/documents
Body: configured as form-data and I have Name, Description and File all configured in the key-value pair interface. Furthermore, File is set as a file type so it allowed me to browse for a file.
When executing this POST the DocumentsController executes the constructor and Application Insights indicates that PostAsync was matched:
Activated Event Time Duration Thread
Application Insights: Trace "Route matched with {action = "PostAsync", controller = "Documents"}. Executing action TdlLims.MediaService.Controller.DocumentsController.PostAsync (TdlLims.MediaService)"
However, it never enters the action. My gut tells me that model binding is failing. This is for two reasons. One, all other pieces of the routing work according the Application Insights. Two, if I remove the parameters entirely, it does enter the action. What I've tried:
Added [FromForm] to the createDocumentRequest
Accepted only an IFormFile into the action, dropping the complex object
Split up the CreateDocumentRequest into three different parameters
And some other things along the way with less signifigance
Now, I'm suspect that when we're setting up Mvc, we may be missing something. We are configuring a few things, but I feel like we're missing a formatter for multipart/form-data somehow. I feel that way because we're using AddMvcCore instead of AddMvc:
.AddAuthorization()
.AddJsonFormatters()
.AddApiExplorer()
.AddJsonOptions(options =>
{
options.SerializerSettings.Converters.Add(new OptionConverter());
options.SerializerSettings.Converters.Add(new StringEnumConverter());
});
Finally, I can confirm the controller is working in general, because I have a GET that is accessible and it makes it to the action:
[HttpGet("{id}")]
public async Task<IActionResult> GetAsync(int id)
In the end, the issue was the size of the file. It would be nice if .NET Core threw an error rather than returning a 200 when something like that happened. I was trying to upload some images, and I'm going to need to figure out the right way to increase the file size, but when I uploaded a small text file the POST worked and the file was deserialized properly into the IFormFile.
I believe the attributes RequestFormLimits and RequestSizeLimit are going to play a role in setting that max file size in the end.
Related
Preface
I recently was assigned a project for college, were using ASP.NET Core 6 Web API, and Entity Framework. Due to the subject at hand the objective is to implement an API without taking any consideration around the structure and routing of it.
So this is a warning: I did not choose the routing nor can I change it, even if slightly.
The actual problem
I have 3 model classes, let's call them Application, Module and Data. A single application has various child modules, while each module has a series of data children.
The issue is that when I want to create a Module or a Data model, the teachers decided to give it a twist and we're forced to take data from the body and the URL.
So that everyone is on the same page ill give an example of how to create a Module.
The url goes like this
POST: https://ip:port/api/OurProjectName/{application}/
POSTBODY:
<?xml version="1.0"?>
<Module><!--here on the root node i can be a bit malleable and name it whatever i want so no issues with DTO's-->
<id>99999</id>
<name>some name</name>
<creation_dt>{the current timestamp}</creation_dt>
</Module>
If the implementation was correct what it would do is go to the controller grab the application string and the Module/ModuleDTO, fetch an Application model from the database where the application string is equal to the field name.
Then inside that function due to our choice of using EF, we would just grab the module sent in the body(or create one in case of a DTO) and associate the respective parent sent in the route parameters.
My failed attempts
Although I talked about modules, the behaviour of data is nearly the same as modules except the teachers decided that for some reason with data you can only create and delete, and you can't list, update, etc... When it comes to posting instead of
POST: https://ip:port/api/OurProjectName/{application}/
I have to do something like
POST: https://ip:port/api/OurProjectName/{application}/{module}
while application this time only serves for checking past errors due to the way the database was structured.
I firstly attempted to do something like
[HttpPost("{application}/{module}")]
[Produces("application/xml")]
[Consumes("application/xml")]public IActionResult Post(string application, string module, [FromBody] Data data)
{
var mod = _context.Modules.SingleOrDefault(m => m.name == module);
if (mod == null)
{
return NotFound();
}
if (mod.parent.name != application)
{
//... this is irrelevant for now
}
data.parent = mod;
// TODO: dereference here... fix later
mod.datas.Add(data);
_context.Add(data);
_context.SaveChanges();
return Ok(data);
}
But it returned the usual error of 415, although this try was mostly hoping that [FromBody] wouldn't complain at the routing as I've had good results with put (although in that situation it kinda follows convention instead of completely breaking it) and to top it off since Data has a navigation field, swagger will iterate the objects until no parents are found so the xml object in the body looked... well like a configuration file.
I then tried to use decorations around the two strings [FromRoute], but it still wouldn't budge, and got an "unsupported media format".
Then I tried to do some custom manual routing (as in no decorations)
here's my startup file that I created with only that purpose in mind (since I otherwise would expect the Program.cs file to get cluttered which is a thing I hate)
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI();
}
var option = new RewriteOptions();
option.AddRedirect("^$", "swagger");
app.UseRewriter(option);
app.UseCors("AllowAll");
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
endpoints.MapControllerRoute(
name: "postDataCustom",
pattern: "api/OurProjectName/{application}/{module}", new {controller = "DataController", action = "Post"});
});
}
I removed the [HttpPost(etc)] and expected to hopefully fix it, but when I checked swagger not only was it missing but the endpoint didn't even exist (I tested with Postman).
I commented it out (the part where I manually set a ControllerRoute) and found some other posts around the subject.
And I saw that I could actually do some kind of dto and put the decorations in each field, this was game breaking as I knew then I would be able to just place a single variable inside the controller function and avoid [FromData] to go insane and parse properly the stuff.
public IActionResult Post(DataDTO data)
{
var mod = _context.Modules.SingleOrDefault(m => m.name == data.module);
if (mod == null)
{
return NotFound();
}
Console.WriteLine(mod.name);
// ...(if it wrote to console I could progress)
return Ok();
}
public class DataDTO
{
[FromRoute]
public string application { get; set; }
[FromRoute]
public string module { get; set; }
[FromBody]
public Data data { get; set; }
public DataDTO(string application, string module, Data data)
{
this.application = application;
this.module = module;
this.data = data;
}
}
It still gave me the error code, this time since I was a bit more skeptical of such a failure, I made a much simpler DTO and routing just to check if I could at least get a 200 code and I did it, the problem is [FromRoute] is pretty much "ignored"
[HttpPost("{module}")]
public IActionResult Post(testeDTO data)
{
Console.WriteLine(data.module);
Console.WriteLine(data.bb);
return Ok();
}
public class testeDTO
{
[FromRoute]
public string? module { get; set; }
[FromBody]
public string bb { get; set; }
public testeDTO(string bb)
{
this.bb = bb;
}
}
Although the route is there and works fine it never assigns the value to module, it seems like whatever is on the body overwrites it (I tried to get around not having duplicate fields by adding the possibility of module being null so I wouldn't be forced to send a module in the body, but no dice, I can't decouple both behaviors).
At this point I'm kinda out of ideas, it's even more frustrating when old documentation gets in the way with search results.
I've also considered using x-www-urlencode, although I'm not sure if it's an option I can take as again the requirements are very restrictive.
TL;DR I can't get a post with parameters in the route to hit successfully the action Post...
Update as of 26/12/2022:
I was playing around the code and weirdly this version "works" i tested it with swagger and it seems to not produce any error, i even checked git to see if added or removed some kind of config or something of the kind but since the last commit(which was uncharacteristic of me as it was a "backup" of sorts) these were the only things that changed
[HttpPost("{module}")]
public IActionResult Post([FromRoute]string module, [FromBody]testeDTO data){
Console.WriteLine(module);
Console.WriteLine(data.bb);
return Ok();
}
...
public class testeDTO{
[FromBody]
public string bb{get;set;}
public testeDTO(string bb){
this.bb = bb;
}
}
I will try to now play around the code to see if i can get to the solution
Step 1)
Go back to your first attempt:
[HttpPost("{application}/{module}")]
[Produces("application/xml")]
[Consumes("application/xml")]
public IActionResult Post(string application, string module, [FromBody] Data data)
{
// Your code
}
Step 2)
Add this line to your Program.cs:
builder.Services.AddControllers().AddXmlSerializerFormatters();
or this line to your ConfigureServices method:
services.AddControllers().AddXmlSerializerFormatters();
Step 3)
Rework your XML to match the parameter name:
<?xml version="1.0"?>
<Data>
<id>99999</id>
<name>some name</name>
<creation_dt>{the current timestamp}</creation_dt>
</Data>
Things should then work.
Step 2) is key, listen to what your being told - 415 is unsupported media type (which you know). So support the media type. I don't know why you think it shouldn't be possible to use a route parameter and a body parameter in the same endpoint but it is.
You may also not want to mix attribute routing and configuration level routing.
I found the answer, apparently the issue revolved around
[FromBody]
//... and
[Consumes("application/xml")]
As the edit on my question suggested i removed the consumes decoration and it started working unfortunately as suggested by the question i cant either change the routing nor can i change the media type it produces and consumes, so my idea was at the time "if i cant use body decorations ill just manually parse the body and keep the routing decorations".
And thats when it hit me XMLserializer requires at least one parameterless constructor to work, and since i had placed parameterless constructors on all other models except on this one, it tricked me into thinking the issue was around the decorators. Ill leave some resources that helped me get into the solution
How to parse xml into objects
Request params documentation
I know that sending multipart requests together with JSON object already had many threads but unfortunately none of them actually resolved the problem for me.
I created controller accepting object containing IFormFile together with some metadata object:
public class DocumentMultipartRequest
{
[FromForm]
public DocumentMetadata Metadata { get; set; }
[FromForm]
public IFormFile File { get; set; }
}
The controller looks like that:
[Consumes("multipart/form-data")]
public async Task<Guid> AddDocument(DocumentMultipartRequest request)
{
}
Apparently Swagger understands my intention correctly because I have string($binary) allowing me to choose a file and object with proper fields inside to fill, unfortunately when I set everything and press "Execute" I will receive "415 Unsupported Media Type" error as result.
How can I fix this problem while maintaining Swagger still understanding my intention, so API is nicely documented?
Setting multiple [Consumes] types didn't help, marking whole DocumentMultipartRequest as [FromForm] will divide DocumentMetadata into different fields f.e. DocumentMetadata.Property1, DocumentMetadata.Property2. The latter will actually work fine and will be properly bound to DocumentMetadata object on backend side, but if possible I would rather accept normal JSON because metadata object may get complicated later on.
I have been assigned to come up with a web service that receives and posts data. However, I am very new to this, and even after looking up multiple examples and trying to follow them, I have a bit of a difficult time understanding.
Referenced examples:
Link 1
Link 2
The code that I have been given as a reference for the model and controller are the following:
Model
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace Webservice.Models.ApiModels {
public class SecondlyReading {
[Key]
public int Id { get; set; }
[Required]
public int Name { get; set; }
[Required]
public string TimeStamp { get; set; }
[Required]
public string Date { get; set; }
[Required]
}
}
Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;
using SmartDBWeb.Data;
using Microsoft.AspNetCore.Authorization;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SmartDBWeb.Models.ApiModels;
using Microsoft.EntityFrameworkCore;
namespace Webservice.Controllers.Api {
[Route("api/[controller]")]
[Authorize]
public class WebserviceController : Controller {
private ApplicationDbContext _context;
public WebserviceController(ApplicationDbContext context) {
_context = context;
}
// GET: api/Webservice
[HttpGet]
public IEnumerable<Webservice> GetSecondlyReadings() {
return _context.Webservice.ToList();
}
// GET api/Webservice/id
[HttpGet("{id}")]
public async Task<IActionResult> GetWebservice(int id) {
var reading = await _context.Webservice.SingleOrDefaultAsync(c => c.Id == id);
if (reading == null) {
return NotFound();
}
return Ok(reading);
}
[HttpPost]
public IActionResult PostWebservice([FromBody]List<Webservice> Readings) {
if (!ModelState.IsValid) {
return BadRequest();
}
foreach (Webservice reading in Readings) {
_context.Webservice.Add(reading);
}
_context.SaveChanges();
return CreatedAtAction("GetWebservice", new { id = Readings[0].Id }, Readings[0]);
}
}
}
My main question is how the use of the above code works in general. What I have found out(might not be correct), is that the the model is the data itself and the controller links the model and view together.
Model: It is basically a table structure for the database. So, whenever you will create an object and set the values and insert the object in the database.
Controller: It is used to deal with the HTTP calls and to link your business logic with the View.
[HttpGet]
This maps to a GET request to the URL api/Webservice without any query parameter. The actions return type is a List, which means that multiple objects should be returned. In your case, when the client accesses api/Webservice, all objects within your _context.Webservice are returned.
[HttpGet("{id}")]
This maps to a GET request as well, but this time it requires a so called Query Parameter. This is an additional piece of information that your client provides to make its request more specific. E.g., they could be requesting api/Webservice?id=1 which would ask you to return the object with an id of 1.
[HttpPost]
This maps to a POST request and asks you to insert or update an object. [FromBody] tells the request processor to convert the so-called Request Body into an object of a given type. The request body is where your client will put entire objects - converted e.g. in JSON format - they want to submit to the server.
So, for the model
public class SecondlyReading {
[Key]
public int Id { get; set; }
[Required]
public int Name { get; set; }
[Required]
public string TimeStamp { get; set; }
[Required]
public string Date { get; set; }
}
This will create a datatable with Id as the primary key because you are using [Key] attribute.
private ApplicationDbContext _context;
This is used to create a database context. You might have also created the following in ApplicationDbContext class
public DbSet<SecondlyReading> WebService{get; set;}
It will create a DbSet with name WebService.
In WEB APIs, POST is used to insert new data. So, here the API
api/webservice
in POST, will be used to insert the data. You can insert the data using any CLIENT like POSTMAN or ARC. You have to set the data in body of request of the HTTP call.
The response of the API can be JSON or XML depending on your output.
I think it's better to read the basics?So that you will understand how normally Web API works
For self reading
https://www.asp.net/web-api
Start with asking yourself how Web Communication generally works. When accessing any website via your browser by typing in an address, what actually happens behind the scenes?
What I found to be very helpful was to open up a new tab in my browser and use Developer Tools (e.g. by right clicking anywhere and then clicking on "Inspect") to observe traffic by switching to the network tab. Access a website of your choice, say: wikipedia.org.
Now a bunch of stuff is going on, but you are interested in the first new entry to your network communication list that should say "www.wikipedia.org". Click on that.
You should now be looking at the "Headers" tab, specifically the request headers. There are two important fields:
Request URL : This tells the server what you want from it. It is a Resource locator, meaning that you want to access a resource from the server, say, a piece of HTML, an image or raw JSON data that you use in your application.
Request Method : This tells the server what you want to do with the resource you are trying to access. Do you want to GET it? Or do you want to PUT some resource on the server? Maybe you want to DELETE it or POST changes to this resource.
Let's go back to your source code.
What you provided above are a Model class and a Controller class.
Your model is a data structure that represents a resource within your web application. Id, Name, Timestamp, Date are attributes of this resource. Depending on your actual use case, you want to create, use, update or delete objects of this model type and decide on their attribute's values.
To allow your clients to do so, you have a controller class. It is the entry point for all web requests that "map" to :
[Route("api/[controller]")]
Map means, when the request URL of your client (remember our example "www.wikipedia.org") matches to the string you defined in your Route, this controller class is used (notice: [controller] will be replaced with the actual name of your controller class, in this case "Webservice".
Within your controller you define Actions. Depending on the Request URL and the Request Method (see above) of your client's request, your web framework decides, which action is called.
[HttpGet]
This maps to a GET request to the URL api/Webservice. The action's return type is a List, which means that multiple objects should be returned. In your case, when the client accesses api/Webservice, all objects within your _context.Webservice are returned.
[HttpGet("{id}")]
This maps to a GET request as well, but this time it requires a so called Query Parameter. This is an additional piece of information that your client provides to make its request more specific. E.g., they could be requesting api/Webservice?id=1 which would ask you to return the object with an id of 1.
[HttpPost]
This maps to a POST request and asks you to insert or update an object. [FromBody] tells the request processor to convert the so-called Request Body into an object of a given type. The request body is where your client will put entire objects - converted e.g. in JSON format - they want to submit to the server.
Now, I hope this makes your code examples a bit clearer to you. You also mentioned the View, so I will quickly explain what that is: Typically, after a request to your server, you respond with some sort of answer. In the most simple case, it is the Response Status that tells the client if everything went smooth. For a GET request, you typically return an object in the Response Body. What you return is called the view. In your example:
return Ok(reading);
converts the object that was retrieved from the database into a machine-readable format (e.g. JSON) and adds the response status "200 OK" to it. This is sent to your client.
So this should give you a good overview on how web frameworks work. I hope I could help you with this rather long read. Let me know if I can clarify anything.
I've got a front end WebAPI written with angular and TypeScript that looks like this.
removeSubset(id: number): ng.IPromise<any> {
return this.$http.post(this.api + '/DeleteStudySubset', id)
.then(this.returnData);
}
returnData = (response: any) => {
return response.data;
};
And the back end version it calls out to is written like this
[HttpPost]
[ResponseType(typeof(IHttpActionResult))]
public async Task<IHttpActionResult> DeleteStudySubset(int id)
{
await _subsetRepo.DeleteStudySubset(id);
return Ok();
}
At first I was getting a URI 404 Error and I couldn't figure it out for the life of me. Then I stumbled across the parameter binding [FromBody] attribute and using it fixed the 404 issue.
So the back end API was rewritten to include the attribute and looked like so
[HttpPost]
[ResponseType(typeof(IHttpActionResult))]
public async Task<IHttpActionResult> DeleteStudySubset([FromBody] int id)
{
await _subsetRepo.DeleteStudySubset(id);
return Ok();
}
From what I think I vaguely understand [FromBody] is telling my back end to not reference the url that is pointing to the back end but search the body of what's being sent to it? Is that right? I don't think I'm explaining my hazy understanding well.
My more, to-the-point question is more or less outlined in the title and is: Is using the [FromBody] attribute on my back end to fix my 404 good practice, or is it more of a hack solution?
It feels like it was too easy of a solution and I'm worried if overall it is a non-elegant solution, and I just slapped a quick-fix on top of a more serious issue. Such as not configuring my front or back end API correctly to work in sync with one another.
Your type script is doing a post, and send the id in the body this is why you've got 404, you should change the typescript to do a get and leave the back-end as is, you do not need a body for the request so get should be just fine (send the id in the url of the get call).
Or best practice it would be that the Delete actions to be actually DELETE http requests, to be more REST compliant, so you need to mark the back-end method with HttpDelete and change the type script to do a delete http request instead.
I would recommend second option.
In the interest making your WebApi RESTful, you should treat your routes as addresses for entities and your http verbs as actions. FromBody should only be used with the verb HttpPost when creating an entity.
Decorate your controller with a route prefix using attribute routing [RoutePrefix()]. Attribute routing should be enabled if you are using WebApi 2. If not just search for enabling attribute routing.
[RoutePrefix("api/study-subset")]
Set the route on the method using attribute routing [Route()]. No need to include [HttpDelete] attribute, WebApi will pick the Delete keyword from the method name. Id will be injected from the route into your method. If you didn't include id in the route, it would be treated as a query string.
[Route("{id}")]
public async Task<IHttpActionResult> DeleteStudySubset(int id)
{
await _subsetRepo.DeleteStudySubset(id);
return Ok();
}
Then update your type script to
return this.$http.delete(this.api + 'api/study-subset/' + id)
I have a web api controller and two GET methods:
public class ImagesController : ApiController {
[HttpGet]
public HttpResponseMessage GetImages() { }
[HttpGet]
public HttpResponseMessage Download([FromUri]int[] ids) { }
}
Why I'm getting multiple actions found error, when trying to reach /api/Images, why both actions are the same?
When you created controller, you have assigned HttpGet to two different methods. Making that you have confused web server when it tries to process your request. Since you are sending GET verb to the controller it self, instead directly to the method, web server can not determinate what method should be invoked.
You can try with /api/Images/GetImages in order to directly hit a method, or remove one of listed.
If you see the Web API feature it work for the selected httm methods like GET,PUT,POST,DELETE.
So if you create two action method with same name it will give error. To avoid this error you have to redefine the DefaultAPI path in route.config file.
Change it to
API/{controller}.....
After changing this acces your API from browser like
Or
Mark as a answer if this resolve your issue.