Why does not working version in asp.net core controller - asp.net-core

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)
{
//...

Related

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.

CreatedAtAction() Cannot Find Route with Matching Parameters

I am attempting to return a CreatedAtAction() result from within an ApiController "NotUnitsController" which indicates a route on a separate ApiController "UnitsController".
Everything works as expected until generating the CreatedAtAction() response. I am receiving the error:
System.InvalidOperationException: No route matches the supplied values.
I am not sure what I am missing. I have tried to remedy the issue with the following:
Verified the spelling of the route parameters on both controllers
Attempted to provide a route name to the [HttpGet] in the UnitsController & reference that name from the NotUnitsController.
Added a / to the [HttpGet("/{unitKey}")] route as suggested in this answer.
The v1 portion of the routes are hard-coded. I found that it could be an issue with dynamic route versioning on this GitHub issue.
I am also able to perform GET requests against the UnitsController endpoint. Only the CreatedAtAction() response is failing.
Here are snippets of the two controllers in question.
NotUnitsController:
[ApiController]
[Route("v1/not-units/{notUnitsKey:guid}/units")]
public class NotUnitsController : ControllerBase
{
[HttpPost]
public async Task<IActionResult> Post(Guid notUnitsKey, Input unitInput)
{
// TODO: Create Unit
var unitKey = Guid.NewGuid();
return CreatedAtAction(actionName: nameof(UnitsController.Get),
controllerName: nameof(UnitsController),
routeValues: new { unitKey },
value: new { unitKey });
}
}
UnitsController:
[ApiController]
[Route("v1/units")]
public class UnitsController : ControllerBase
{
[HttpGet("{unitKey:guid}")]
public async Task<IActionResult> Post(Guid unitKey)
{
// TODO: Get Unit by key
var unit = $"My Unit with Id: {unitKey}";
return Ok(unit);
}
}
Any help would be greatly appreciated.
Probably you should use nameof(UnitsController.Post) as the actionName value, and new { unitKey = unitKey } as the routeValues value on your CreatedAtAction response.

New Api return Internal Server Error

I create asp.Net Core API like, after that I create a controller like this:
[Route("api/Email")]
public class EmailController : Controller
{
private readonly IEmailSender _emailSender;
public EmailController(IEmailSender emailSender)
{
_emailSender = emailSender;
}
[Route("Send")]
[HttpPost]
public IActionResult Index(string Email)
{
_emailSender.SendEmailAsync(Email, "Confirm your account","correo desde api");
return View();
}
Problem occcurs when I try to execute this path with Postman as:
http://localhost:3703/api/Email/Send
with JSON raw parameter like:
{
"Email":"myemail#gmail.com"
}
It just returns 500 Internal Server Error, I try to put breakpoint into api Send method and it never hitted. I need to do another configuration to execute a simple method of controller? Regards
Based on the comment to your question the constructor of your controller is not hitted.
So you need to make sure that the IEmailSender is correctly configured for dependency injection.
So in your Startup class go to ConfigureServices method and add the following line if it not exists:
services.AddScoped<IEmailSender, MyEmailSenderImplementation>();
MyEmailSenderImplementation should be the class that impelments IEmailSender interface.

How to Get Route Data from Middleware for ASPNETCORE OData request?

I have the following Middleware class which gets the route data for the current request.
If you perform a Get on the Values Controller you will see the context.GetRouteData() returns a value and is not null. I have wired Swagger\Swashbuckle into the attached project to make this easier to demo.
However, if you call the Blog OData controller (http://localhost:40946/odata/Blog), context.GetRouteData() returns null.
Does anyone know how to access the RouteData from middleware for an OData request?
public class TestMiddleware
{
protected readonly RequestDelegate _next;
public TestMiddleware(RequestDelegate next)
{
this._next = next;
}
public virtual async Task Invoke(HttpContext context)
{
var routeData = context.GetRouteData();
await this._next.Invoke(context);
}
}
Link to sample solution demonstrating the issue.
Looks like the OData Middleware isn't providing the routing info as a IRoutingFeature to the context. Link to Source Code
Not sure the root cause - but as a workaround you could use
var httpRequestFeature = context.Features[typeof(IHttpRequestFeature)] as IHttpRequestFeature;
var path = httpRequestFeature?.Path;

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.