Enable CORS in ASP.NET Core Web API

Hello friends,

As we know that in Web API, CORS is by default disabled due to security reasons. and hence if a client tries to access API in different server and port, you can end up with error as “Origin http://localhost:xxxx is not allowed by Access-Control-Allow-Origin

To enable it in ASP.NET Core Web API, there are few steps involved as following.

Go to startup.cs

Put code as follows inside ConfigureServices method

services.AddCors();

Put code as follows inside Configure method

app.UseCors(
options => options.WithOrigins("http://localhost", "https://localhost")
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);

In the WithOrigins array, you can add or remove the client URL based on your local machine domain and port settings.

Hope you found the post useful. Please let me know your comment below.

Changing default route in ASP.NET MVC

Hello friends,

As we know that ASP.NET MVC by default takes following setting available in RouteConfig file (under App_Start folder).

routes.MapRoute(

name: “Default”,

url: “{controller}/{action}/{id}”,

defaults: new { controller = “Home”, action = “Index”, id = UrlParameter.Optional }

);

This means when you run the application, Home controller will be invoked and it’s Index method will be executed by taking parameter id (if any).

you can change this behavior, if it’s making sense to you.

For example if you want to invoke Store controller and It’s Browse method while loading the application, you just need to change few things (controller and action values) as below.

routes.MapRoute(

name: “Default”,

url: “{controller}/{action}/{id}”,

defaults: new { controller = “Store”, action = “Browse”, id = UrlParameter.Optional }

);

Optionally you may also change the id parameter but I would personally recommend not to change (to keep it generic) unless there is some unavoidable reason.

Hope you liked the post. Please share your comments.