Swagger 500 error in web api - asp.net

When I access the swagger url: http//localhost:50505/swagger/index. I got the 500 error.
Please help me to figure out.
namespace BandwidthRestriction.Controllers
{
[Route("api/[controller]")]
public class BandwidthController : Controller
{
private SettingDbContext _context;
private readonly ISettingRespository _settingRespository;
public BandwidthController(ISettingRespository settingRespository)
{
_settingRespository = settingRespository;
}
public BandwidthController(SettingDbContext context)
{
_context = context;
}
// GET: api/Bandwidth
[HttpGet]
public IEnumerable<Setting> GetSettings()
{
return _settingRespository.GetAllSettings();
}
// GET: api/Bandwidth/GetTotalBandwidth/163
[HttpGet("{facilityId}", Name = "GetTotalBandwidth")]
public IActionResult GetTotalBandwidth([FromRoute] int facilityId)
{
// ...
return Ok(setting.TotalBandwidth);
}
// GET: api/Bandwidth/GetAvailableBandwidth/163
[HttpGet("{facilityId}", Name = "GetAvailableBandwidth")]
public IActionResult GetAvailableBandwidth([FromRoute] int facilityId)
{
// ...
var availableBandwidth = setting.TotalBandwidth - setting.BandwidthUsage;
return Ok(availableBandwidth);
}
// PUT: api/Bandwidth/UpdateBandwidthChangeHangup/163/10
[HttpPut]
public void UpdateBandwidthChangeHangup([FromRoute] int facilityId, [FromRoute]int bandwidth)
{
_settingRespository.UpdateBandwidthHangup(facilityId, bandwidth);
}
// PUT: api/Bandwidth/UpdateBandwidthChangeOffhook/163/10
[HttpPut]
public void UpdateBandwidthChangeOffhook([FromRoute] int facilityId, [FromRoute] int bandwidth)
{
_settingRespository.UpdateBandwidthOffhook(facilityId, bandwidth);
}
// POST: api/Bandwidth/PostSetting/163/20
[HttpPost]
public bool PostSetting([FromRoute] int facilityId, [FromRoute]int bandwidth)
{
//
return false;
}
}
The corresponding configuration code in Startup.cs is
public void ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<SettingDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddMvc();
services.AddSwaggerGen();
services.ConfigureSwaggerDocument(options =>
{
options.SingleApiVersion(new Info
{
Version = "v1",
Title = "Bandwidth Restriction",
Description = "Api for Bandwidth Restriction",
TermsOfService = "None"
});
// options.OperationFilter(new Swashbuckle.SwaggerGen.XmlComments.ApplyXmlActionComments(pathToDoc));
});
services.ConfigureSwaggerSchema(options =>
{
options.DescribeAllEnumsAsStrings = true;
//options.ModelFilter(new Swashbuckle.SwaggerGen.XmlComments.ApplyXmlTypeComments(pathToDoc));
});
// Add application services.
services.AddTransient<ISettingRespository, SettingRespository>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action}/{facilityId?}");
routes.MapRoute(
name: "",
template: "{controller}/{action}/{facilityId}/{bandwidth}");
});
app.UseSwaggerGen();
app.UseSwaggerUi();
}
In firefox: the error is unable to load swagger ui

Your route attributes are wrong. The routes for GetAvailableBandWidth and GetTotalBandWidth are both mapped to the route api/bandwidth/{facilityId} and not, as your comments suggests, to api/Bandwidth/GetAvailableBandwidth/{facilityId} and api/Bandwidth/GetTotalBandwidth/{facilityId}. The same goes, sort of, for your put methods.
When you register two identical routes, one will fail and throws an exception. Hence the http status code 500.
You can fix it like this:
// GET: api/Bandwidth/GetTotalBandwidth/163
[HttpGet("GetTotalBandwidth/{facilityId}", Name = "GetTotalBandwidth")]
public IActionResult GetTotalBandwidth(int facilityId)
{
// ...
return Ok(setting.TotalBandwidth);
}
// GET: api/Bandwidth/GetAvailableBandwidth/163
[HttpGet("GetAvailableBandwidth/{facilityId}", Name = "GetAvailableBandwidth")]
public IActionResult GetAvailableBandwidth(int facilityId)
{
// ...
var availableBandwidth = setting.TotalBandwidth - setting.BandwidthUsage;
return Ok(availableBandwidth);
}
// PUT: api/Bandwidth/UpdateBandwidthChangeHangup/163/10
[HttpPut("UpdateBandwidthChangeHangup/{facilityId}/{bandwidth}")]
public void UpdateBandwidthChangeHangup(int facilityId, int bandwidth)
{
_settingRespository.UpdateBandwidthHangup(facilityId, bandwidth);
}
// PUT: api/Bandwidth/UpdateBandwidthChangeOffhook/163/10
[HttpPut("UpdateBandwidthChangeOffhook/{facilityId}/{bandwidth}")]
public void UpdateBandwidthChangeOffhook(int facilityId, int bandwidth)
{
_settingRespository.UpdateBandwidthOffhook(facilityId, bandwidth);
}
Please note I removed the [FromRoute] attributes because they are not necessary.

Related

Cannot set a custom contract resolver in web api configuration

How can I set a custom contract resolver in web api configuration? My code is relatively new and has no custom contract resolver till now.
I have added no other customization besides routing.
I tried in three different ways and none worked:
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//attempt 1
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CustomContractResolver();
//attempt 2
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CustomContractResolver();
//attempt 3
JsonConvert.DefaultSettings = () => new JsonSerializerSettings
{
ContractResolver = new CustomContractResolver()
};
}
The custom contract resolver code, breakpoint never reaches here when I'm debugging:
public class CustomContractResolver : CamelCasePropertyNamesContractResolver
{
protected override string ResolvePropertyName(string propertyName)
{
var regex = new Regex(#"([_])(\w)");
if (regex.IsMatch(propertyName))
{
var result = regex.Replace(propertyName.ToLower(), (match) => { return match.Groups[2].Value.ToUpper(); });
return result;
}
else
return base.ResolvePropertyName(propertyName);
}
}
Is there something that is missing?
Edit 1:
I'm using ASP.NET WebApi 5.2.1 AND MVC 5.2.7, JSON.NET (Newtonsoft.Json) v13.0.1 (and already tried the old v12)
My Global Asax is very simple as well:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register); //<- web api configuration
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes); //<- mvc configuration
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
The MVC RouteConfig class:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.ashx/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
Edit 2
Here is some test web api controllers:
using System.Web.Http;
namespace Kronos.Web.Geolocalizacao.Controllers.Api
{
public class TestController : ApiController
{
[HttpGet]
public TestModel Obtain()
{
return new TestModel { CODE_IDENTIFICATION = 1, DEFAULT_DESCRIPTION = "TEST DAT THING" };
}
}
public class TestModel
{
public decimal CODE_IDENTIFICATION { get; set; }
public string DEFAULT_DESCRIPTION { get; set; }
}
}
Used the Tabbed Postman chrome addon to test
Postman tests
Your problem has nothing to do with how you are registering your global settings -- setting config.Formatters.JsonFormatter.SerializerSettings.ContractResolver is correct as per this question. Your problem is that Json.NET does not call ResolvePropertyName() when the contract resolver also has a NamingStrategy -- and your base class CamelCasePropertyNamesContractResolver does indeed have a naming strategy.
This can be verified by checking the current Json.NET reference source for DefaultContractResolver.SetPropertySettingsFromAttributes():
if (namingStrategy != null)
{
property.PropertyName = namingStrategy.GetPropertyName(mappedName, hasSpecifiedName);
}
else
{
property.PropertyName = ResolvePropertyName(mappedName);
}
Broken demo fiddle #1 here.
If I simply modify your CustomContractResolver to inherit from DefaultContractResolver (which has a null NamingStrategy by default), then it works:
public class CustomContractResolver : DefaultContractResolver
{
readonly NamingStrategy baseNamingStrategy = new CamelCaseNamingStrategy();
protected override string ResolvePropertyName(string propertyName)
{
var regex = new Regex(#"([_])(\w)");
if (regex.IsMatch(propertyName))
{
var result = regex.Replace(propertyName.ToLower(), (match) => { return match.Groups[2].Value.ToUpper(); });
return result;
}
else
return baseNamingStrategy.GetPropertyName(propertyName, false);
}
}
Fixed demo fiddle #2 here.
However, a cleaner solution would be to replace your custom contract resolver with a custom naming strategy:
public class CustomNamingStrategy : CamelCaseNamingStrategy
{
public CustomNamingStrategy() : base() { }
public CustomNamingStrategy(bool processDictionaryKeys, bool overrideSpecifiedNames) : base(processDictionaryKeys, overrideSpecifiedNames) { }
public CustomNamingStrategy(bool processDictionaryKeys, bool overrideSpecifiedNames, bool processExtensionDataNames) : base(processDictionaryKeys, overrideSpecifiedNames, processExtensionDataNames) { }
readonly Regex regex = new Regex(#"([_])(\w)");
protected override string ResolvePropertyName(string name)
{
if (regex.IsMatch(name))
{
var result = regex.Replace(name.ToLower(), (match) => { return match.Groups[2].Value.ToUpper(); });
return result;
}
return base.ResolvePropertyName(name);
}
}
And then configure it in settings like so:
settings.ContractResolver = new DefaultContractResolver
{
// Set the constructor parameters as per your preference. These values are consistent with CamelCasePropertyNamesContractResolver
NamingStrategy = new CustomNamingStrategy(processDictionaryKeys: true, overrideSpecifiedNames: true),
};
Demo fiddle #3 here.

Get items count from OData api

I'm working on ASP.NET Core 3.1 project where I use OData for the rest api. The problem is that when I try to fetch the count of the items in the collection with this query: http://someurl?$count=true, OData returns me an array of all the items, instead of the count. I read a lot of articles about OData and nothing helped, so I'm quite confused.
Here is a working demo , you could refer to
Install Package Microsoft.AspNetCore.OData -Version 7.4.0
Model
public class Student
{
public Guid Id { get; set; }
public string Name { get; set; }
public int Score { get; set; }
}
Controller , EnableQuery attribute enables an endpoint to have OData capabilities
[Route("api/[controller]")]
[ApiController]
public class StudentsController : ControllerBase
{
[HttpGet]
[EnableQuery()]
public IEnumerable<Student> Get()
{
return new List<Student>
{
new Student
{
Id = Guid.NewGuid(),
Name = "Vishwa Goli",
Score = 100
},
new Student
{
Id = Guid.NewGuid(),
Name = "Josh McCall",
Score = 120
}
};
}
}
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers(mvcOptions =>
mvcOptions.EnableEndpointRouting = false);
services.AddOData();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
//app.UseEndpoints(endpoints =>
//{
// endpoints.MapControllers();
//});
app.UseMvc(routeBuilder =>
{
// enable Selection, Expansion, Count, Filter, OrderBy for all routes under “odata/”
routeBuilder.Expand().Select().Count().OrderBy().Filter();
routeBuilder.MapODataServiceRoute("odata", "odata", GetEdmModel());
});
}
private IEdmModel GetEdmModel()
{
var edmBuilder = new ODataConventionModelBuilder();
edmBuilder.EntitySet<Student>("Students");
return edmBuilder.GetEdmModel();
}
Result:
Reference:
https://devblogs.microsoft.com/odata/experimenting-with-odata-in-asp-net-core-3-1/
https://medium.com/#sddkal/using-odata-controller-in-net-core-apis-63b688585eaf

Api Routing in .net core 3.0

I am new to .net core and I want to set a MapRoute to my api.
I config endpoint in startup.cs like
app.UseEndPoints(endpoints=>{
endpoints.MapController("defaultApi","v1/{controller="cont"}/{action}/{id?}");
endpoints.MapController("defaultNonActionApi","v1/{controller="cont"}/{id?}")l
endpoints.MapHealthChecks("/healthz");
});
and in controller.cs
[ApiController]
[Route("[controller]")]
public class contController:ControllerBase{
[HttpGet]
public ActionResult Get(){}
}
The config in useEndpoints is useless, if I goto https://localhost:port/v1/cont it return a 404 and if i goto https://localhost:port/cont it can return an expected result.
It seems like the RouteAttribute override the config in useEndpoints but I can't remove RouteAttribute for an ApiController.
I know change Route("[controller]") to Route("v1/[controller]") can solve this problem, but what I want is something more global that can be configured in startup.cs.
Thanks.
Here is a simple demo like below:
1.Create a custom MvcOptionsExtensions:
public static class MvcOptionsExtensions
{
public static void UseGeneralRoutePrefix(this MvcOptions opts, IRouteTemplateProvider routeAttribute)
{
opts.Conventions.Add(new RoutePrefixConvention(routeAttribute));
}
public static void UseGeneralRoutePrefix(this MvcOptions opts, string prefix)
{
opts.UseGeneralRoutePrefix(new RouteAttribute(prefix));
}
}
public class RoutePrefixConvention : IApplicationModelConvention
{
private readonly AttributeRouteModel _routePrefix;
public RoutePrefixConvention(IRouteTemplateProvider route)
{
_routePrefix = new AttributeRouteModel(route);
}
public void Apply(ApplicationModel application)
{
foreach (var selector in application.Controllers.SelectMany(c => c.Selectors))
{
if (selector.AttributeRouteModel != null)
{
selector.AttributeRouteModel = AttributeRouteModel.CombineAttributeRouteModel(_routePrefix, selector.AttributeRouteModel);
}
else
{
selector.AttributeRouteModel = _routePrefix;
}
}
}
}
2.Register in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews(o => { o.UseGeneralRoutePrefix("v1"); });
}
// 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.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
3.Controller:
[ApiController]
[Route("[controller]")]
public class contController:ControllerBase{
[HttpGet]
public ActionResult Get(){}
}

How to store list object in session variable using asp.net core. And how to fetch values from session variable from the View?

Using asp.net core how to create a session variable to store the list kind of objects and how to retrieve the values from the view
was trying
HttpContext.Session.SetString("Test", listObject);
.
First, you need to add more config at Startup class.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDistributedMemoryCache();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromSeconds(10);
options.Cookie.IsEssential = true;
});
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseDeveloperExceptionPage();
app.UseStatusCodePages();
app.UseStaticFiles();
app.UseSession();
app.UseMvc(routes =>
{
// Default Route
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
//Add the following extension methods to set and get serializable objects:
public static class SessionExtensions
{
public static T GetComplexData<T>(this ISession session, string key)
{
var data = session.GetString(key);
if (data == null)
{
return default(T);
}
return JsonConvert.DeserializeObject<T>(data);
}
public static void SetComplexData(this ISession session, string key, object value)
{
session.SetString(key, JsonConvert.SerializeObject(value));
}
}
public IActionResult Index()
{
List<BookingModel> data = new List<BookingModel>();
for (int i = 1; i < 10; i++)
{
BookingModel obj = new BookingModel
{
BookingId = i,
BookingRefNo = $"00{i}",
FullName = $"A{i}",
MobileNo = $"(00)-{i}",
Email = $"abc{i}#gmail.com"
};
data.Add(obj);
}
HttpContext.Session.SetComplexData("loggerUser", data);
return View();
}
public IActionResult Privacy()
{
List<BookingModel> data = HttpContext.Session.GetComplexData<List<BookingModel>>("loggerUser");
return View();
}
And you can visit this link to refer more: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/app-state?view=aspnetcore-2.2#session-state
Hope to help, my friend :))

Getting internal server error (500) in response after insert/update

CRUD operation works fine with the database but i am getting 500 internal server error for POST/PUT operation. I am getting 200 for GET/DELETE.
I worked with crud operation in ASP.NET and my code is running in prod. I have a requirement to migrate that to .NET Core. While testing i found that CRUD operations are working fine and i can see the changes related to data inside the SQL database but for Insert/Update, I am getting 500 error in response.
Code for .NET Framework (Working):-
public class ActivityUpdatesController : ApiController
{
private PortfolioMgmtEntities db = new PortfolioMgmtEntities();
// GET: api/ActivityUpdates
public IQueryable<ActivityUpdate> GetActivityUpdates()
{
return db.ActivityUpdates;
}
[Route("api/activityUpdates/getByProjectId")]
public IQueryable<ActivityUpdate> getActivityUpdatesByProjectId(int projectId)
{
IQueryable<ActivityUpdate> activityUpdates = from r in db.ActivityUpdates
where r.ProjectID == projectId
select r;
return activityUpdates;
}
// GET: api/ActivityUpdates/5
[ResponseType(typeof(ActivityUpdate))]
public IHttpActionResult GetActivityUpdate(int id)
{
ActivityUpdate activityUpdate = db.ActivityUpdates.Find(id);
if (activityUpdate == null)
{
return NotFound();
}
return Ok(activityUpdate);
}
// PUT: api/ActivityUpdates/5
[ResponseType(typeof(void))]
public IHttpActionResult PutActivityUpdate(int id, ActivityUpdate activityUpdate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != activityUpdate.RecordID)
{
return BadRequest();
}
db.Entry(activityUpdate).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ActivityUpdateExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/ActivityUpdates
[ResponseType(typeof(ActivityUpdate))]
[Route("api/activityUpdates/create")]
public IHttpActionResult PostActivityUpdate(int projectId, [FromBody] ActivityUpdate activityUpdate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
activityUpdate.ProjectID = projectId;
activityUpdate.UpdatedDate = DateTime.Now;
db.ActivityUpdates.Add(activityUpdate);
db.SaveChanges();
IQueryable<ActivityUpdate> activityUpdates = from au in db.ActivityUpdates
where au.ProjectID == projectId
select au;
return CreatedAtRoute("DefaultApi", new { controller = "ActivityUpdates" }, activityUpdates);
}
// DELETE: api/ActivityUpdates/5
[ResponseType(typeof(ActivityUpdate))]
public IHttpActionResult DeleteActivityUpdate(int id)
{
ActivityUpdate activityUpdate = db.ActivityUpdates.Find(id);
if (activityUpdate == null)
{
return NotFound();
}
db.ActivityUpdates.Remove(activityUpdate);
db.SaveChanges();
return Ok(activityUpdate);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ActivityUpdateExists(int id)
{
return db.ActivityUpdates.Count(e => e.RecordID == id) > 0;
}
}
WebAPiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.EnableCors(new EnableCorsAttribute("*", "*", "GET,PUT,POST,DELETE"));
}
Code for .NET Core (Not Working):-
public class ActivityUpdatesController : Controller
{
private aeportfoliomgmtdbContext db = new aeportfoliomgmtdbContext();
// GET: api/ActivityUpdates
public IQueryable<ActivityUpdates> GetActivityUpdates()
{
return db.ActivityUpdates;
}
[HttpGet]
[Route("api/activityUpdates/getByProjectId")]
public IQueryable<ActivityUpdates> getActivityUpdatesByProjectId(int projectId)
{
IQueryable<ActivityUpdates> activityUpdates = from r in db.ActivityUpdates
where r.ProjectId == projectId
select r;
return activityUpdates;
}
[HttpPost]
[Route("api/activityUpdates/create")]
public IActionResult PostActivityUpdate(int projectId, [FromBody] ActivityUpdates activityUpdate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
activityUpdate.ProjectId = projectId;
activityUpdate.UpdatedDate = DateTime.Now;
db.ActivityUpdates.Add(activityUpdate);
db.SaveChanges();
IQueryable<ActivityUpdates> activityUpdates = from au in db.ActivityUpdates
where au.ProjectId == projectId
select au;
return CreatedAtRoute("DefaultApi", new { controller = "ActivityUpdates" }, activityUpdates);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ActivityUpdateExists(int id)
{
return db.ActivityUpdates.Count(e => e.RecordId == id) > 0;
}
}
startup.cs
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().AddJsonOptions(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment 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.UseSpaStaticFiles();
app.UseCors("CorsPolicy");
app.UseMvc(routes =>
{
routes.MapRoute(
name: "DefaultApi",
template: "api/{controller}/{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");
}
});
}
}
I am unable to find where is the mistake. Could you please help me to solve this issue? Any help will be appreciated.
If you want to return GetActivityUpdates like web api, try to define the route name above the GetActivityUpdates method.
[HttpGet("api/activityUpdates/GetActivityUpdates", Name = "GetActivityUpdates")]
public IQueryable<ActivityUpdates> GetActivityUpdates()
{
return db.ActivityUpdates;
}
[HttpGet]
[Route("api/activityUpdates/getByProjectId")]
public IQueryable<ActivityUpdates> getActivityUpdatesByProjectId(int projectId)
{
IQueryable<ActivityUpdates> activityUpdates = from r in db.ActivityUpdates
where r.ProjectId == projectId
select r;
return activityUpdates;
}
[HttpPost]
[Route("api/activityUpdates/create")]
public IActionResult PostActivityUpdate(int projectId, [FromBody] ActivityUpdates activityUpdate)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
activityUpdate.ProjectId = projectId;
activityUpdate.UpdatedDate = DateTime.Now;
db.ActivityUpdates.Add(activityUpdate);
db.SaveChanges();
IQueryable<ActivityUpdates> activityUpdates = from au in db.ActivityUpdates
where au.ProjectId == projectId
select au;
return CreatedAtRoute("GetActivityUpdates", activityUpdates);
}
Please try to return Ok() from your post method not created route and check is it working or not. If it is work then may be you does not define the route that you use in created route.

Resources