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());
Related
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();
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.
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.
I have a .net core 3.0 application and I am trying to implement Swashbuckle package . So I can do a http get request.
I have a controller like this:
[Route("api/products")]
[ApiController]
public class ProductValuesController : Controller
{
private DataContext context;
public ProductValuesController(DataContext data)
{
this.context = data;
}
[HttpGet("{id}")]
public Product GetProduct(long id)
{
return context.Products.Find(id);
}
public IActionResult Index()
{
return View();
}
}
and the startup.cs file looks like this:
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)
{
string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(connectionString));
services.AddControllersWithViews();
services.AddRazorPages();
services.AddSwaggerGen(options => {
options.SwaggerDoc("v1", new OpenApiInfo { Title = "SportsStore", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IServiceProvider services)
{
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?}");
});
app.UseSwagger();
app.UseSwaggerUI(options => {
options.SwaggerEndpoint("/swagger/v1/swagger.json",
"SportsStore API");
});
// SeedData.SeedDatabase(services.GetRequiredService<DataContext>());
}
}
But if I start the application and browse to:
https://localhost:5001/swagger/v1/swagger.json
I will see this error:
NotSupportedException: Ambiguous HTTP method for action - ServerApp.Controllers.ProductValuesController.Index (ServerApp). Actions require an explicit HttpMethod binding for Swagger 2.0
So my quesiton is: what I have to change, so that it will work?
Thnak you.
I had this issue as well, it looks like the IActionResult Index() is causing the issue. You can do as mentioned above and decorate it with [NonAction] attribute and then it should fix it.
Decorate your public non - REST methods in the Controller as [NoAction]
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."