Does someting like AcceptRequestType exists in ASP.NET Core Web API? - asp.net-web-api2

I would like to have a single controller action to accept different types as request and I would like to have them automatically generated with Swashbuckle. There is possibility of annotating Web API method with Attribute ProducesResponseType on method of controller like this:
[HttpGet()]
[ProducesResponseType(typeof(typeName))]
public Task<IActionResult> Method()
{
//...
}
Does exists a similar option for request types? Something like this:
[HttpGet()]
[AcceptRequestType(typeof(concreteTypeName1))]
[AcceptRequestType(typeof(concreteTypeName2))]
public Task<IActionResult> Method(AbstractType model)
{
//...
}

You can use the following attribute:
[Consumes("application/json")]

Related

How can I add links to other controller methods in generated OpenAPI specs using attributes in ASP.NET Core?

I am using SwaggerGen to generate an OpenAPI spec for our API, and would like to add links between certain endpoints.
OpenAPI 3.0 Links
Is there a way to add an attribute to the controller method that links to another controller method?
For example, if I currently have something like
[HttpPost]
[Route("~/users")]
[ProducesResponseType(typeof(ResponseObject<UserId>), StatusCodes.Status200OK)]
public async Task<IActionResult> CreateUser(...)
{
// Create user
}
[HttpGet]
[Route("~/users/{userId}")]
[ProducesResponseType(typeof(ResponseObject<User>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetUser(...)
{
// Get newly created user
}
Could I somehow link them like
[HttpPost]
[Route("~/users")]
[ProducesResponseType(typeof(ResponseObject<UserId>), StatusCodes.Status200OK)]
[Link(nameof(GetUser), "UserId")]
public async Task<IActionResult> CreateUser(...)
{
// Create user
}
[HttpGet]
[Route("~/users/{userId}")]
[ProducesResponseType(typeof(ResponseObject<User>), StatusCodes.Status200OK)]
public async Task<IActionResult> GetUser(...)
{
// Get newly created user
}
to generate the "links" field as shown in the OpenAPI 3.0 spec linked above?

Why does not working version in asp.net core controller

I want to use api version in my .net core project.Then search web and find that's solution.
Even though do exactly all solutions,but I can't get desired result.
So if any can help me,Please show me..
I add Microsoft.AspNetCore.Mvc.Versioning 4.0.0 Package in my project and ..
StartUp.cs
Then in my Controller Add Rout Attribute as Shown :
[ApiController]
[Authorize]
[Route("v{version:apiVersion}/[Controller]")]
[ApiVersion("1.0")]
public class SellerController : Controller
{
private readonly IBus _client;
private readonly string AppBaseUrl = MyHttpContext.AppBaseUrl;
//private readonly IGetUrl _globalUrl;
public SellerController(IBus client/*, IGetUrl globalUrl*/)
{
_client = client;
//_globalUrl = globalUrl;
}
[HttpGet("/Sellers/{SellerId}")] // Dashboard
public async Task<IActionResult> Info(long SellerId)
{
...
}
}
With these code I expected that I can send request to 'Info' method by this url :
But that's not working and get 404 error code status.. when I delete "/v1.0" from url and send request, that's working. I will be glad to help me .. Thanks
In your code, we can find that you applied [HttpGet("/Sellers/{SellerId}")] with route
template begin with / to Info action method, which don't get combined with route templates applied to the controller. To make request to 'Info' method, you could use below URL.
https://localhost:5090/sellers/17
I expected that I can send request to 'Info' method by this url : https://localhost:5090/v1.0/sellers/17
To achieve your requirement, you can try to modify the code like below.
[HttpGet("/v{version:apiVersion}/Sellers/{SellerId}")]
public async Task<IActionResult> Info(long SellerId)
{
//...
//for testing purpose
return Ok(SellerId);
}
Test Result
Update:
If you'd like to include v{version:apiVersion} in route template of controller level attribute routing, you can try to apply [HttpGet("{SellerId}")] to Info action method and make request with https://localhost:5090/v1.0/seller/17.
[ApiController]
[Authorize]
[Route("v{version:apiVersion}/[Controller]")]
[ApiVersion("1.0")]
public class SellerController : Controller
{
[HttpGet("{SellerId}")] // Dashboard
public async Task<IActionResult> Info(long SellerId)
{
//...

How do I get Route attribute to work in .net core api?

So I added a controller to a blank asp.net CORE Api.
public class IsAliveController : ControllerBase
{
[HttpPost]
[HttpGet]
[Route("isalive")]
public object Get()
{
return "I'm alive";
}
}
Then I try to access it via https://localhost:44361/isalive
and I get no response. Do I need to make some modifications to my Startup.cs?
First why have you declared your method both as a get and a post request? you can remove the post attribute.
By default your routing must start with your controller name, add this:
[Route("[controller]")]
[ApiController]
public class IsAliveController : ControllerBase
{
[HttpGet]
public object Get()
{
return "I'm alive";
}
}
Now when you call https://localhost:44361/isalive you will receive the expected response.
There are two solutions to your problem:
#1 Your controller Name is IsAlive and you have added a route attribute on your action method as isAlive, so this would work only if you call using this Url
https://localhost:44361/isalive/isalive
#2 Remove the Route attribute from the action method
public class IsAliveController : ControllerBase
{
[HttpGet]
public object Get()
{
return "I'm alive";
}
}
and you will be able to access using Url
https://localhost:44361/isalive
Found the issue. The template I choose (using Visual studio 2019) was:
Asp.net core web app > Web Application
The startup file in this template is missing a line that I needed to add:
app.UseEndpoints(endpoints =>
{
//Add this line
endpoints.MapControllers();
});
After adding that line the endpoint works without any changes to the controller.

ASP.Net Core required parameter binding fails to fail using FromBody

I'm developing an Asp.Net Core API.
My controller declaration
[ApiController]
public class BarController : Controller
{
...
}
My endpoint looks like this
[HttpPost, Route("bars")]
public async Task<ActionResult> DoAsync(
[FromBody] UpdateBars command)
{
// Do something with the command
return Ok(result);
}
The command looks like this
public class UpdateBars
{
[Required]
public IEnumerable<string> Ids { get; set; }
// ... more properties
}
Compatibility level is set to 2.1
public IServiceProvider ConfigureSharedServices(IServiceCollection services)
{
// ...
services.AddMvc()
.AddControllersAsServices()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// ...
}
Old question: I'd expect this to return a 400 bad request with a missing Ids parameter, but it fails to return the binding error.
What am I doing wrong?
Updated question: I'd expect this to return a 400 bad request with a missing or empty Ids parameter. The response is as expected if the parameter is missing (null), but returns 200 ok if it is an empty collection.
Is it possible to change something so that I get a bad request when the parameter is present but empty?
You probably didn't put a [ApiController] attribute on your controller.
By default the validation is not 'automatic'.
If you don't want to put that attribute on your controller, you will have to validate the model yourself, in following way:
[HttpPost, Route("bars")]
public async Task<ActionResult> DoAsync(
[FromBody] UpdateBars command)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
// Do something with the command
return Ok(result);
}
You have more controll in that way, but if you just need to return a BadRequest with the model state, it will happen automatically if you put the [ApiController] on the controller.
Also in that case it will mark all action parameters as [FromBody], so putting that attribute on params is not needed
You should add the [ApiController] attribute. In that case, an automatic HTTP 400 response containing error details is returned when model state is invalid. For more information, see Automatic HTTP 400 responses. Automatic HTTP 400 responses.

Get the route value from url in webapi attribute routing

I have a webAPI controller which is like
Public class TestController:APIController
{
[Route(“Api/Test/{testId}/SubTest”)]
Public void Post(int subTestid)
{
}
}
Our requirement is to get the value of testId from the url inside the post method.
Could anyone suggest the best way to achieve this.
Looking at this link: http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2
The string "customers/{customerId}/orders" is the URI template for the
route. Web API tries to match the request URI to the template. In this
example, "customers" and "orders" are literal segments, and
"{customerId}" is a variable parameter.
public class OrdersController : ApiController
{
[Route("customers/{customerId}/orders")]
[HttpGet]
public IEnumerable<Order> FindOrdersByCustomer(int customerId) { ... }
}
It seems that you need to change subTestid to testId so it will be a match.