No overload for method 'UseRouting' takes 1 arguments in Razorpages - c#

im trying to show data from my database. I used this website to write my code https://www.c-sharpcorner.com/article/how-to-connect-mysql-with-asp-net-core/ . Everything is going good but in Startup.cs I get this error error CS1501: No overload for method 'UseRouting' takes 1 arguments
I don't know what to do. Here is the code:
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.Add(new ServiceDescriptor(typeof(pictureContext), new pictureContext(Configuration.GetConnectionString("DefaultConnection"))));
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=picture}/{action=Index}/{id?}"
);
});
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages();
});

The article you are following is for MVC, not Razor Pages. It looks like it was written before Razor Pages was released. The UseRouting method doesn't take a single argument (hence the error message), and you don't need to configure routes for controllers in a Razor Pages app, so just call
app.UseRouting();

Related

ASP.NET Core: The SPA default page middleware could not return the default page '/index.html' because it was not found

I am trying to deploy my Angular and .Net Core app using IIS but I get the following error message
The SPA default page middleware could not return the default page
'/index.html' because it was not found, and no other middleware
handled the request. Your application is running in Production mode,
so make sure it has been published, or that you have built your SPA
manually. Alternatively you may wish to switch to the Development
environment.
This is what my startup.cs looks like
namespace GammaFramework {
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; }
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add
services to the container. public void
ConfigureServices(IServiceCollection services) {
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddMvc(option => option.EnableEndpointRouting = false);
//services.AddDbContext<GammaFrameworkContext>(options =>
// options.UseSqlServer(Configuration.GetConnectionString("GammaFrameworkContext")));
services.AddDbContext<GammaFrameworkContext>();
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
services.AddScoped(typeof(IDataRepository<>), typeof(DataRepository<>));
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddControllersWithViews(options =>
{
options.AllowEmptyInputInBodyModelBinding = true;
});
}
// This method gets called by the runtime. Use this method to
configure the HTTP request pipeline. public void
Configure(IApplicationBuilder app, IWebHostEnvironment env) { if
(env.IsDevelopment()) {
app.UseDeveloperExceptionPage(); } else {
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts(); }
app.UseCors("CorsPolicy");
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
} } }
inside my wwwroot folder I have:
api folder: webapi project
app folder: build angular folder
web.config: copied from webapi project

API post not decting raw json model

once again, I'm trying to hit post method of controller but the method is not catching json model. rest, all types of headers are working instead of json post.
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
readonly string CorsPolicy = "MyPolicy";
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add Cors
services.AddCors(o => o.AddPolicy(CorsPolicy, builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors(CorsPolicy);
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
Can anyone please guide me on what should I need to change?
or where am I wrong in this?
Try matching case of field name, and include quotes, e.g. "DepartmentId": 0
And confirm request has Content-Type: application/json
since you are using json , you have to add [FromBody] to the action
pubic ActionResult Post([FromBody] department)
also fix json in postman
{
"DepartmentId": 0,
"DepartmentName": "bpu"
}
also to support no sensitive letter case add these options to startup
using Newtonsoft.Json.Serialization;
.....
services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver());

Set Default Redirect For Authorize Tag

Asp.net Core 3+ has some different conventions - bare with me.
I have a controller that I am trying to use Authentication middleware. I used the default 'scaffolding' when creating a new core project in VS2019. Used the MVC project template for asp.net core 3.1.
I have my controller that has the [Authorize] tag.
[Authorize]
public class AgentController : Controller
{
}
In a past life.. I knew where to set the default redirect if Unauthorized.
It is forcing a redirect to /Identity/SignIn -a default set of razor pages that seems to be built in. I need it to redirect to a specific controller/action. Account/SignIn
Here is my startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<AgentUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddControllersWithViews();
//services.AddRazorPages();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
You can configure the specific path in ConfigureServices (in Startup):
services.ConfigureApplicationCookie(config =>
{
config.Cookie.Name = "Identity.Cookie";
config.LoginPath = "/Account/SignIn";
});
When you add services.AddRazorPages() and services.AddControllersWithViews() at the same time, you need to avoid the same routing.

ASP.NET Core weird URL parsing. Single query string parameter

I want to pass a string parameter to an action. Acreated a method in the HomeController with the following signature:
[HttpGet]
public IActionResult TestView([FromQuery] string test)
{
return View(test);
}
This is my configuration class:
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
When I go to https://localhost:5001/Home/TestView it works ok
When I add a query string ?test=myvalue it fails to find the view. It tries to locate the view using weird paths.
InvalidOperationException: The view 'myvalue' was not found. The following locations were searched:
/Views/Home/myvalue.cshtml
/Views/Shared/myvalue.cshtml
Is that a bug?
The behavior is occurring because you passed the value "myvalue" as the first parameter of your returned ViewResult, which is the viewname parameter:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.viewresult.viewname?view=aspnetcore-5.0
If you change your return statement to:
return View();
Then you won't be passing a view name parameter and it will then search for a view named TestView.

MVC controller API access in Blazor not working with .NET Core 3.0

I am trying to setup a Blazor Server side app, but running into an issue with the app reading data from my MVC Controller API. I have a controller for my model Study called StudyController. I can access the json data for my GetAll() route "/studies" when I launch the Blazor app, but the Blazor app is not reading the data. Code below:
StudyController:
[Route("studies")]
[ApiController]
public class StudyController : ControllerBase
{
private StudyRepository _ourCustomerRespository;
public StudyController()
{
_ourCustomerRespository = new StudyRepository();
}
//[Route("Studies")]
[HttpGet]
public List<Study> GetAll()
{
return _ourCustomerRespository.GetStudies();
}
}
Razor page function section trying to access data:
#functions {
IList<Study> studies = new List<Study>();
protected async Task OnInitAsync()
{
HttpClient Http = new HttpClient();
studies = await Http.GetJsonAsync<List<Study>>("/studies");
}
}
Startup.cs configuration code:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc(options => options.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.AddControllers();
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddSingleton<WeatherForecastService>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseMvcWithDefaultRoute();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub();
endpoints.MapFallbackToPage("/_Host");
});
}
It appears the issue was that OnInitAsync() no longer works in the latest version of Blazor. I switched to using OnInitializedAsync() and that data loaded correctly.
You Can get any exception like
"An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set."

Categories