What is the essence of Endpoints in ASP.NET? - c#

I am pretty new to the C# and ASP.NET and now I am trying to understand what does the Endpoint in ASP.NET mean, or what is the essence of this concept, thank you!
Example:
app.UseMvc(route =>
{
route.MapRoute(name:"default", template:"{controller=Home}/{action=index}/{id?}");
});
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
What are the differences when using this two method?

In your context an endpoint is a URL that causes a netcore server to do something (run some code) when a browser connects to the server, quotes the url as part of a http request and possibly includes a body or other parameter data
Per the comments, UseMvc/UseSignalR on 2.2 were effectively replaced by a single UseEndpoints in 3.0. The netcore migration guide discusses the differences in depth and makes recommendations on how to switch from UseMvc to UseEndpoints
Per my comment, I strongly recommend you shouldn't seek to establish a totally different dev environment to what your course teaches via/is expecting to see submissions of assignments in, just because you have a Mac and can't/won't make it the same environment the institution uses. Handing in an app that uses 3.0 to a tutor marking it on a machine that uses 2.2 may well get you fewer points because it doesn't compile

Related

Aspnetcore API route Template based on Host

I have a set of APIs in an ASP.NET Core (.NET6) project that are exposed both internally (private) and through an API gateway. When served privately, API urls are of the form service.internal/api/v1/resource which is achieved with a RouteAttribute on the ApiController:
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
public class ResourceController : ControllerBase
{
// actions
}
When accessed via our api gateway, however, the /api/ component of the url is absent, ie. gateway.com/v1/resource. The gateway performs a transformation on the Url which adds in the extra path segment for the internal/proxied request.
This all works "fine" except in a few circumstances. The primary issue I'm having is with link/url generation for requests coming through the gateway. Location headers added by CreatedAt and link headers generated with IUrlHelper include the /api/ segment of the route with the gateways hostname rendering them invalid. I also have some issues with swagger but I believe they should resolve themselves if I can solve this.
Question: Is there a way to make the route template dynamic based on the host name (which would not be a compile time constant, ie. from config)? For example for requests coming from gateway.com, the route template would be v{version:apiVersion}/[controller] and otherwise would be api/v{version:apiVersion}/[controller]?
It doesn't need to be attribute driven if there's a different way. But my understanding is that the ApiControllerAttribute makes attribute routing required and I wouldn't want to lose the other benefits of that.
If I can get this to work, I'd be able to update the gateway and not have it add the /api/ segment to the proxied urls and it should remove any issues with swagger since the proper paths would be detected by the api explorer.
Unfortunately I have no idea where to start looking. I reviewed some of the routing docs but I didn't see anything that would do the job. I admit I'm out of my league here with minimal aspnetcore experience.
If it matters we are using endpoint routing:
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});

Mapping Subdomains to Areas in ASP.Net Core 3

What I want to achieve
Mapping my normal domain e.g. example.com to no area if possible.
Mapping my subdomain e.g. blog.example.com to a area named blog.
What I have found
There are actually quite a lot of posts regarding to this topic, especially mapping subdomains to areas.
From SO:
area-and-subdomain-routing
asp-net-core-mapping-subdomains-to-areas
Others:
danylkoweb.com
benjii.me
web.archive.org
And there are probably even more.
Problem
But there is one big problem, in ASP.Net Core 3 they changed a lot of things, one of them being the routing in general, see mircosoft's devblog. Basically they changed it so everything should now be endpoints.
All the classes e.g. MvcRouteHandler and interfaces e.g. IRouter are basically obsolete now, at least from my understanding. After a while googling around and diggin' in the GitHub repositories I couldn't find anything useful.
Additional information
I am using SDK 3.0.100-preview6-012264, but trying to upgrade to
SDK 3.0.100-preview7-012821 as soon as possible.
I am using a reserve proxy (nginx) which passes the request to the ASP.Net Core Server.
You said all requests pass on nginx but nothing said about nginx redirection, did you try to use nginx to do that, just redirect the sub-domain to domain using /etc/nginx/nginx.conf.
server {
server_name sub.domain.co;
location / {
return 301 $scheme://domain.co/BlogSite$request_uri;
}
}
(BlogSite is your area routing on ASP.Net Core Server.)
To give an update to this whole situation, with the release of .Net Core 3 you can now make use of the RequireHost method.
This would look something like the following:
app.UseEndpoints(endpoints =>
{
endpoints.MapAreaControllerRoute(
name: "Home",
areaName: "Home",
pattern: "{controller=Home}/{action=Index}")
.RequireHost("localhost:5001", "sub.domain.com");
}
If you remove the Area in the pattern parameter, like in the example, you can achieve exactly that. It is still somewhat hacky, but a lot cleaner.
Note, that you would have to put a RequireHost on all of the endpoints in order to get proper default route matching.

Swashbuckle fails in asp.net core with NotSupportedException exception

I followed this example on how to add swashbuckle in my asp.net core 2.2 project.
As soon as I run the project I get following error:
An unhandled exception occurred while processing the request.
NotSupportedException: HTTP method "GET" & path "{id}" overloaded by actions - dotnet1.Server.Controllers.UsersController.GetById
(dotnet1.Server),dotnet1.Server.Controllers.ValuesController.Get
(dotnet1.Server). Actions require unique method/path combination for
Swagger 2.0. Use ConflictingActionsResolver as a workaround
Don't understand what is the issue here.
try putting get method:
[HttpGet("{id}")]
you must differentiate your methods and map correctly.
I encountered a similar and resolved it by configuring the MVC routes to be more explicit.
I wanted to have HTTPGET /users/{id} for a single user and HTTPGET /users?role={role}.
So, based on what I read in a comment on this Github issue linked below, I did the following when configuring my MVC routes.
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}");
routes.MapRoute(
name: "single",
template: "{controller=Home}/{id}");
});
Related Github Issue
This is common while using Swagger. The real error here is this
Actions require unique method/path combination for Swagger 2.0. Use
ConflictingActionsResolver as a workaround
The swagger seems to work. This is a general error we get when our controllers are named differently.
1) Check for duplicate names in action methods. Change the name of the error causing GET action method to something else and try?
I have faced this error in my aspnet core app and fixed it like that.
Your issue could be related to this
Swashbuckle will raise an exception if it encounters multiple actions with the same path (sans query string) and HTTP method
The link has a solution for your problem.

ASP.NET Core 2 CORS not enabled

I'm developing a web application based on an Angular 6 client and ASP.NET Core WebAPI for web services.
At the moment (initial development phase) i have a simple architecture that consists of two web services, one that manages authentication and identities, the other one that holds the applicative logic (business logic, updating db, ecc.).
I'm using JWT Bearer token for client authentication.
Everything works fine with my authentication service, but when I try to call the application service I obtain this error in the Chrome browser console:
Failed to load http://localhost:59207/api/Files/Upload: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 500.
This error is preceded by another one:
POST http://localhost:59207/api/Files/Upload 500 (Internal Server Error)
Is, in some way, the second error I get related to the Internal Server Error it is preceded by?
I test my POST call from Postman and everything works fine, no server-side errors and the data i want back from my service is returned.
I already put in place everything I know about CORS in ASP.NET Core.
Startup class method named "ConfigureServices" contains, as first row:
services.AddCors(options =>
{
options.AddPolicy("AllowAll",
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials();
});
});
Then this is called in the "Configure" method:
app.UseCors("AllowAll");
Also I put the EnableCors Attribute on every controller class like this:
[EnableCors("AllowAll")]
Anyone has an idea of how I can get out of this mess?
From what I get, this is how CORS is intended to be used and I already got it running this way on other projects (but never with ASP.NET Core 2).
Thank you in advance
This may not be an answer to your situation, but I've run into this issue quite often in the past. It's a Chrome issue when talking between two localhosts upon POST requests.
Try using another browser and see if it works; if so, you can continue using Chrome by disabling Security
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security
hope this helps.

Cannot See ODataController Derived Action URLs in Swagger UI

I am currently trying to use Swagger UI to interact with my OData enabled Web API.
Versions for the bits and bobs are as follows:
.Net 4.5.2,
Web API 2.2,
NuGet package Microsoft.AspNet.OData 6.0.0 for OData 4.0 endpoints,
Swashbuckle 5.3.2,
Swashbuckle.Core 5.3.2,
Swashbuckle.OData 3.0.0.
My application has a SwaggerConfig.cs and a WebApiConfig.cs as expected. And I have followed many of the instructions in this article, this article and a few others on the web.
When I launch my API through Visual Studio, I initially get a new browser tab with the local host URL. If I append the word "/swagger" (no quotes) at the end of that URL, I get a nice Swagger UI in the same tab. This tab shows the name of of my API but not much else. I don't see any of the individual URL interfaces for the Actions exposed by my ODataController derived Controller. Moreover, underneath the displayed name of the URL, all I have is [ base url: , api version: v1 ] where "v1" is coming in from SwaggerConfig.cs (same with the API name).
I know I can talk to the API from Swagger UI because I can arrive at the "Get" action of the Controller by modifying the displayed URL appropriately. The actions created were the standard Get, Put, Post, Patch, Delete ones. But I cannot see any of these in the Swagger UI.
This is because I am new to this and obviously have missed out or miscoded stuff to link everything correctly. I have made very little change to SwaggerConfig.cs and left most of the things as they were when it was created. The significant change I have made was adding this line:
c.CustomProvider(defaultProvider => new ODataSwaggerProvider(defaultProvider, c, GlobalConfiguration.Configuration));
Based on this info, if anyone can guide me in the direction of what pieces could be missing or developed incorrectly, I would greatly appreciate it. If you had any further questions for me, I would be happy to respond in the comments.
It turns out that because I had been recreating the application, Entity Framework was no longer creating the database for me since it was trying to use a name it had already recently used (a known EF bug). So I refractored the name of the database to something else. After this, things were plain sailing.
This negates my comment: "I know I can talk to the API from Swagger UI because I can arrive at the "Get" action of the Controller by modifying the displayed URL appropriately. The actions created were the standard Get, Put, Post, Patch, Delete ones. But I cannot see any of these in the Swagger UI."
Clearly this was me not understanding the issue clearly. But by going through the steps again one by one, I was able to find the problem and come to the desired place :)

Categories

Resources