I cannot get an Endpoint to receive media-type text/csv.
I have a .Net Core 3.1 API app that needs to have an endpoint that receives a CSV. I figured adding this would be fine:
[HttpPost("CSV")]
[Consumes("text/csv")]
public async Task<IActionResult> InsertCsv([FromBody] string values)
{
return Ok($"here is the data!\r\n{values}");
}
However, in Postman sending the request returns this error:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.13",
"title": "Unsupported Media Type",
"status": 415,
"traceId": "|e2e74cae-4824ee592543d555." }
With that error figured I would have to do something in the ConfigureServices however, I cannot find anything. I did find you need to add for XML:
services.AddControllers().AddXmlDataContractSerializerFormatters();
Cannot figure out what do to add text/csv.
Related
I have a Web API project created in .NET 6 and a Controller action with the following signature:
[HttpPost("my/route")]
public async Task<IActionResult> Post([FromBody]MyRequest myRequest)
If I post with a JSON payload that cannot be model bound to a MyRequest, then I get the following error message:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-6f50cde5f3c24d3f9ae15432b4878299-dff20b1783488d15-00",
"errors": {
"$.UserId": [
"The JSON value could not be converted to System.Guid. Path: $.UserId | LineNumber: 1 | BytePositionInLine: 16."
]
}
}
How can I customize this response so that I return different JSON attributes and values?
You can customise the responses by creating new API Behaviour for validation failures, See https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-6.0#validation-failure-error-response-1
Please see my c# core api code as following:
[HttpPost]
public bool Save([FromBody] string data,[FromQuery] ICollection<int> list)
{
var result = true;
return result;
}
and angular post call as following:
postAction(data: any, list: number[]): Observable<any> {
let params = new HttpParams().set('scopes', JSON.stringify(list));
return this.httpClient.post( `${this.apiUri}/Save`,data, { params });
}
with these i'm getting an "One or more validation errors occurred" error with status code 400.
can't we use FromBody and FromQuery at same time ?
Update 1:
Code Details
400
Undocumented
Error:
Response body
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "00-b6e1d156b5ff1940a6186060c4902663-36e8ff61a6d6374b-00",
"errors": {
"$": [
"'s' is an invalid start of a value. Path: $ | LineNumber: 0 | BytePositionInLine: 0."
]
}
}
The code does not reach the controller because ASP.NET Core runs a validation to assert that the data in the request are valid and can be mapped to the parameters of your action. When sending data to ASP.NET Core, it is important that the structure of the data meets the expectations of the action, if not, the framework returns a BadRequest response (status code 400).
In your code, the query parameter is named list, in the Angular code, you send it as scopes. These should match, so you should rename one of them (or use the constructor parameter of FromQuery to set the name to scopes).
In addition, remove the JSON.stringify for the query parameter and just assign the array. The url will then have several values for scopes, e.g.:
/mycontroller/?scopes=1&scopes=3&scopes=5
ASP.NET Core Web API parses the URI in a different way and will assign the values to the scopes parameter.
I've been having a little issue implementing AspNetCore.HealthChecks.UI correctly. I have two endpoints that run health checks using the "live" and "ready" as tags. Both endpoints work work as expected but after implementing the HealthChecksUI, The health check results displayed is always "Unhealthy
An error occurred while sending the request." even though the endpoint returns "Healthy" from postman. Please see screenshots and relevant code snippets and configurations.
AppSettings Configuration
"HealthChecksUI": {
"HealthChecks": [
{
"Name": "Crowd Funding App",
"Uri": "http://localhost:5001/healthui"
}
],
"EvaluationTimeinSeconds": 10,
"MinimumSecondsBetweenFailureNotifications": 60
}
In the Configure function of the startup class, I have the following code.
I have a model validation that uses a custom header:
[HttpGet("")]
public async Task<IActionResult> GetData([FromHeaderCustomerId, CustomerId] string customerId)
These 2 attributes read from header and validate the header. If the validation does not pass, I get something liket that:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "someId",
"errors": {
"X-Customer-ID": [
"The customerId field is required."
]
}
}
That works just fine, but I do have additional headers that I do not read in every request as a parameter. I would like to validate these custom headers in some simple way so that Asp.Net Core would generate 400 response the same way it does when I use model validation for a paramter.
Is it possible to do?
I have an Angular front-end app and an ASP.NET Core back-end app. Everything was fine until I decided to migrate from ASP.NET Core 2.2 to 3.0-preview-9.
For example, I have a DTO class:
public class DutyRateDto
{
public string Code { get; set; }
public string Name { get; set; }
public decimal Rate { get; set; }
}
And an example JSON request:
{
"name":"F",
"code":"F",
"rate":"123"
}
Before migration, this was a valid request because 123 was parsed as a decimal. But now, after migration, I am getting an HTTP 400 error with this body:
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|3293cead-4a35656a3ae5e95b.",
"errors": {
"$.rate": [
"The JSON value could not be converted to System.Decimal. Path: $.rate | LineNumber: 0 | BytePositionInLine: 35."
]
}
}
In addition, it doesn't hit the first line of my method—it is thrown before, probably during model binding.
If I send the following, however:
{
"name":"F",
"code":"F",
"rate":123
}
Everything works fine. But this means that I need to change every request I have written so far. The same thing is true with all other data types (int, bool, …).
Does anybody know how I can avoid this and make it work without changing my requests?
ASP.NET Core 3 uses System.Text.Json instead of Newtonsoft.Json (aka JSON.NET) for handling JSON. JSON.NET supports parsing from a string into a decimal, but System.Text.Json does not. The easiest thing to do at this stage is to switch back to using JSON.NET, as described in the docs:
Add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson.
Update Startup.ConfigureServices to call AddNewtonsoftJson.
services.AddMvc()
.AddNewtonsoftJson();
It would be more correct to pass the decimal as a JSON number, but it's clear that's not going to be an option for you.