ASP.NET MVC Multiple actions were found that match the request - asp.net-mvc

I'm trying to support both web api and normal controllers.
I have defined different methods for different actions but looks like something is wrong as I'm getting following error again and again
{"Message":"An error has occurred.","ExceptionMessage":"Multiple actions were found that match the request:
\r\nPostFilter on type imaserver.Controllers.OrdersController\r\nPostOrder on type imaserver.Controllers.OrdersController",
"ExceptionType":"System.InvalidOperationException",
"StackTrace":"
at System.Web.Http.Controllers.ApiControllerActionSelector.ActionSelectorCacheItem.SelectAction(HttpControllerContext controllerContext)\r\n
at System.Web.Http.Controllers.ApiControllerActionSelector.SelectAction(HttpControllerContext controllerContext)\r\n
at System.Web.Http.ApiController.ExecuteAsync(HttpControllerContext controllerContext, CancellationToken cancellationToken)\r\n
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()"}
Here is my code:
RouteConfig
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
"CDN",
"cdn/{directory}/{file}",
new { controller = "CDN", action = "Download", directory = UrlParameter.Optional, file = UrlParameter.Optional }
);
routes.MapRoute(
name: "API",
url: "api/{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}",
defaults: new { controller = "Home", action = "Index" }
);
}
}
OrderController
public class OrdersController : ApiController
{
private FoodDeliveryEntities db = new FoodDeliveryEntities();
// GET: api/Orders
public IQueryable<Order> GetOrders()
{
db.Configuration.ProxyCreationEnabled = false;
return db.Orders;
}
// GET: api/Orders/5
[ResponseType(typeof(Order))]
public IHttpActionResult GetOrder(long id)
{
db.Configuration.ProxyCreationEnabled = false;
Order order = db.Orders.Find(id);
if (order == null)
{
return NotFound();
}
return Ok(order);
}
// PUT: api/Orders/5
[ResponseType(typeof(void))]
public IHttpActionResult PutOrder(long id, Order order)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != order.Id)
{
return BadRequest();
}
db.Entry(order).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!OrderExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST: api/Orders/filter
[HttpPost]
public IHttpActionResult PostFilter(OrderFilter orderFilter)
{
db.Configuration.ProxyCreationEnabled = false;
if (orderFilter.OrderType != null)
return Ok(db.Orders.Include(o => o.OrderItems.Select(i => i.Item)).Include(c => c.Customer).OrderByDescending(o => o.PickupDate).Where(o => o.OrderType.Equals(orderFilter.OrderType)));
else if (orderFilter.Status != null)
return Ok(db.Orders.Include(o => o.OrderItems.Select(i => i.Item)).Include(c => c.Customer).OrderByDescending(o => o.PickupDate).Where(o => o.Status.Equals(orderFilter.Status)));
else
return Ok(db.Orders.Include(o => o.OrderItems.Select(i => i.Item)).Include(c => c.Customer));
}
// POST: api/Orders
[ResponseType(typeof(Order))]
public IHttpActionResult PostOrder(Order order)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Configuration.ProxyCreationEnabled = false;
order.Status = "New";
order.CreatedAt = DateTime.Now;
order.UpdatedAt = DateTime.Now;
db.Orders.Add(order);
db.SaveChanges();
foreach (var orderItem in order.OrderItems)
{
orderItem.OrderId = order.Id;
orderItem.CreatedAt = DateTime.Now;
orderItem.UpdatedAt = DateTime.Now;
orderItem.IsActive = true;
}
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = order.Id }, order);
}
// DELETE: api/Orders/5
[ResponseType(typeof(Order))]
public IHttpActionResult DeleteOrder(long id)
{
Order order = db.Orders.Find(id);
if (order == null)
{
return NotFound();
}
db.Orders.Remove(order);
db.SaveChanges();
return Ok(order);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool OrderExists(long id)
{
return db.Orders.Count(e => e.Id == id) > 0;
}
public partial class OrderFilter
{
public string Status { get; set; }
public string OrderType { get; set; }
}
}
I also tried to rename PostFilter to Filter but of no use
I am firing this URL:
http://somewebsite/api/Orders/filter
POST
What am I doing wrong?

Since you inherit from ApiController, you can only have 1 POST, GET, PUT or DELETE actions, to have more, update each of your actions to assign its unique route by decorating the methods with the
[ActionName("put_here_your_action_rout")]
attribute.
// POST: api/Orders/filter
[HttpPost]
[ActionName("filter")]
public IHttpActionResult PostFilter(OrderFilter orderFilter)
{
db.Configuration.ProxyCreationEnabled = false;
if (orderFilter.OrderType != null)
return Ok(db.Orders.Include(o => o.OrderItems.Select(i => i.Item)).Include(c => c.Customer).OrderByDescending(o => o.PickupDate).Where(o => o.OrderType.Equals(orderFilter.OrderType)));
else if (orderFilter.Status != null)
return Ok(db.Orders.Include(o => o.OrderItems.Select(i => i.Item)).Include(c => c.Customer).OrderByDescending(o => o.PickupDate).Where(o => o.Status.Equals(orderFilter.Status)));
else
return Ok(db.Orders.Include(o => o.OrderItems.Select(i => i.Item)).Include(c => c.Customer));
}
For the ApiController, the real name of your methods is irrelevant, you need to use the ActionName attribute.

Related

Why does authorization fails when I publish on IIS in aspnet core?

I have used aspnet core identity for login functionality in my webapp. I have published my webapp on IIS. It loads perfectly but when I enter username and password and navigate to action methods bearing authorize attribute the applications fails. But renaming the action methods with AllowAnonymous attribute solves my issue!!
Note: The application runs perfect with authorize attribute when I debug it locally(localhost)
how could I fix this?
startup.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using OnlineExam.Models.LoginModel;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.Authorization;
using OnlineExam.Models.CandidateLogin;
namespace OnlineExam
{
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();
services.AddEntityFrameworkSqlServer();
services.AddIdentity<OnlineExam.Models.UserAccountModel.ApplicationUser, IdentityRole>(options =>
{
options.User.AllowedUserNameCharacters = default;
options.User.RequireUniqueEmail = false;
})
.AddEntityFrameworkStores<Models.UserAccountModel.OnlineExamDBContext>();
//services.AddMvc();
services.AddMvc(options =>
{
var policy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
options.Filters.Add(new AuthorizeFilter(policy));
});
services.AddDbContext<OnlineExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
services.AddDbContext<OnlineExam.Models.AdminQuestionModel.OnlineExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
services.AddDbContext<CandidateLoginDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
services.AddDbContext<OnlineExam.Models.CandidateExam.CandidateExamDBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("LoginConnection")));
services.AddScoped<OnlineExam.Models.UserAccountModel.OnlineExamDBContext>();
//services.AddScoped<OnlineExam.Controllers.AdminQuestionController>();
}
// 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.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
});
}
}
}
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using OnlineExam.Models.UserAccountModel;
using System.Web;
using Newtonsoft.Json;
using System.Text.Json;
namespace OnlineExam.Controllers
{
[AllowAnonymous]
public class UserAccountsController : Controller
{
private readonly OnlineExamDBContext _context;
private readonly UserManager<OnlineExam.Models.UserAccountModel.ApplicationUser> _userManager;
private readonly SignInManager<OnlineExam.Models.UserAccountModel.ApplicationUser> _signInManager;
List<ApplicationUser> userList = new List<ApplicationUser>();
public UserAccountsController(OnlineExamDBContext context, UserManager<OnlineExam.Models.UserAccountModel.ApplicationUser> userManager, SignInManager<OnlineExam.Models.UserAccountModel.ApplicationUser> signInManager)
{
_context = context;
_userManager = userManager;
_signInManager = signInManager;
}
// GET: UserAccounts
public async Task<IActionResult> Index()
{
return View(await _context.ApplicationUser.ToListAsync());
}
// GET: UserAccounts/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null)
{
return NotFound();
}
var userAccount = await _context.ApplicationUser
.FirstOrDefaultAsync(m => m.UserAccountId == id);
if (userAccount == null)
{
return NotFound();
}
return View(userAccount);
}
// GET: UserAccounts/Create
[HttpGet]
public IActionResult Create()
{
var viewmodel = new ApplicationUser();
return View(viewmodel);
}
// POST: UserAccounts/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(ApplicationUser userModel)
{
if (ModelState.IsValid)
{
bool userCheck = IsUserExists(userModel.UserName);
if (userCheck == false)
{
var user = new OnlineExam.Models.UserAccountModel.ApplicationUser();
user = userModel;
var result = await _userManager.CreateAsync(user, userModel.UserPassword);
if (result.Succeeded)
{
return Logout();
}
else
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error.Description);
}
}
}
else
{
ModelState.AddModelError("","Username already exist");
}
}
return View(userModel);
}
// GET: UserAccounts/Edit/5
public async Task<IActionResult> Edit(int? id)
{
if (id == null)
{
return NotFound();
}
var userAccount = await _context.ApplicationUser.FindAsync(id);
if (userAccount == null)
{
return NotFound();
}
return View(userAccount);
}
// POST: UserAccounts/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, [Bind("UserAccountId,UserName,UserPassword,UserFullName,UserGender,UserPriviledge,UserDesignation,UserDepartment,UserMailId,UserAddress,UserMobileNo,UserPhoto,UserQualification")] UserAccount userAccount)
{
if (id != userAccount.UserAccountId)
{
return NotFound();
}
if (ModelState.IsValid)
{
try
{
_context.Update(userAccount);
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!UserAccountExists(userAccount.UserAccountId))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToAction(nameof(Index));
}
return View(userAccount);
}
// GET: UserAccounts/Delete/5
public async Task<IActionResult> Delete(int? id)
{
if (id == null)
{
return NotFound();
}
var userAccount = await _context.ApplicationUser
.FirstOrDefaultAsync(m => m.UserAccountId == id);
if (userAccount == null)
{
return NotFound();
}
return View(userAccount);
}
// POST: UserAccounts/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
var userAccount = await _context.ApplicationUser.FindAsync(id);
_context.ApplicationUser.Remove(userAccount);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
private bool UserAccountExists(int id)
{
return _context.ApplicationUser.Any(e => e.UserAccountId == id);
}
[AllowAnonymous]
[HttpGet]
public IActionResult Login()
{
return View();
}
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> Login(ApplicationUser login)
{
///var user = new OnlineExam.Models.UserAccountModel.ApplicationUser { UserName = login.UserName };
//TempData["user"] = user;
var result = await _signInManager.PasswordSignInAsync(login.UserName, login.UserPassword, true, false);
if (result.Succeeded)
{
var userData = from x in _context.ApplicationUser.Where(x => x.UserName == login.UserName).ToList()
select new { x.UserFullName, x.Email, x.UserAddress ,x.UserName
,x.UserPhoto ,x.UserMobileNo,x.UserGender,x.UserQualification,
x.UserDepartment,x.UserDesignation,x.UserPriviledge,x.UserAccountId};
//List<ApplicationUser> userList = new List<ApplicationUser>();
foreach (var item in userData)
{
userList.Add(new ApplicationUser
{ UserFullName =item.UserFullName, UserAccountId= item.UserAccountId,UserName=item.UserName,
Email=item.Email,UserDepartment=item.UserDepartment,UserGender=item.UserGender,
UserPriviledge=item.UserPriviledge, UserPhoto=item.UserPhoto, UserAddress=item.UserAddress
});
//userList.Add(new ApplicationUserReplica { UserAccountId = item.UserAccountId });
}
//List<ApplicationUserReplica> userList= new List<ApplicationUserReplica>();
//userList.Add(new ApplicationUserReplica { UserFullName = userData.Select(x => x.UserFullName).ToString()});
// userList.Add(new ApplicationUserReplica { UserAccountId =Convert.ToInt32(userData.Select(x => x.UserAccountId)) });
var sdata=JsonConvert.SerializeObject(userList);
TempData["userData"] = sdata;
return RedirectToAction(nameof(LoginInfo));
}
else
{
ModelState.AddModelError("", "Please enter you username and password correctly");
}
return View(login);
}
public bool IsUserExists(string userName)
{
int c=_context.ApplicationUser.Where(x => x.UserName == userName).Count();
if (c >= 1)
{
return true;
}
else
{
return false;
}
}
[AllowAnonymous]
public ActionResult Logout()
{
_signInManager.SignOutAsync();
return RedirectToAction(nameof(Login));
}
[AllowAnonymous]
[HttpGet]
public IActionResult LoginInfo()
{
userList=JsonConvert.DeserializeObject<List<ApplicationUser>>(TempData["userData"].ToString());
TempData.Keep();
foreach(var item in userList)
{
TempData["userId"] = item.UserAccountId;
}
return View();
}
}
}

Mvc5 Error Please :( [duplicate]

This question already has answers here:
The ViewData item that has the key 'XXX' is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'
(6 answers)
Closed 5 years ago.
Hello Everybody Good day My English is not very good Poo Do not Look Mvc 5 New Start My Blog Site.
I got the error
I List Categories, I Provide Entrance to Other Areas
When I Select Photo When I Select Time
I uploaded the picture and I share the link. I am taking this mistake. Could you show me the way to this error? Thank you for your time
namespace MvcSite.Controllers
{
public class AdminMakaleController : Controller
{
MvcblogDb db = new MvcblogDb();
// GET: AdminMakale
public ActionResult Index()
{
var makale = db.Makale.ToList();
return View(makale);
}
// GET: AdminMakale/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: AdminMakale/Create
public ActionResult Create()
{
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi");
return View();
}
// POST: AdminMakale/Create
[HttpPost]
public ActionResult Create(Makale makale, string Etiket, HttpPostedFile Foto)
{
if (ModelState.IsValid)
{
if (Foto != null)
{
WebImage img = new WebImage(Foto.InputStream);
FileInfo fotoinfo = new FileInfo(Foto.FileName);
string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
img.Resize(800, 350);
img.Save("~/Uploads/MakaleFoto/" + newfoto);
makale.Foto = "/Uploads/MakaleFoto/" + newfoto;
}
if (Etiket != null)
{
string[] etiketdizi = Etiket.Split(',');
foreach (var i in etiketdizi)
{
var yenietiket = new Etiket { EtiketAdi = i };
db.Etiket.Add(yenietiket);
makale.Etiket.Add(yenietiket);
}
}
db.Makale.Add(makale);
db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
// GET: AdminMakale/Edit/5
public ActionResult Edit(int id)
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makales == null)
{
return HttpNotFound();
}
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi", makales.KategoriId);
return View(makales);
}
// POST: AdminMakale/Edit/5
[HttpPost]
public ActionResult Edit(int id, HttpPostedFile Foto, Makale makale)
{
try
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (Foto != null)
{
if (System.IO.File.Exists(Server.MapPath(makales.Foto)))
{
System.IO.File.Delete(Server.MapPath(makales.Foto));
}
WebImage img = new WebImage(Foto.InputStream);
FileInfo fotoinfo = new FileInfo(Foto.FileName);
string newfoto = Guid.NewGuid().ToString() + fotoinfo.Extension;
img.Resize(800, 350);
img.Save("~/Uploads/MakaleFoto/" + newfoto);
makale.Foto = "/Uploads/MakaleFOTO/" + newfoto;
makales.Baslik = makale.Baslik;
makales.İcerik = makale.İcerik;
makales.KategoriId = makale.KategoriId;
db.SaveChanges();
}
return RedirectToAction("Index");
}
catch
{
ViewBag.KategoriId = new SelectList(db.Kategori, "KategoriId", "KategoriAdi", makale.KategoriId);
return View(makale);
}
}
// GET: AdminMakale/Delete/5
public ActionResult Delete(int id)
{
var makale = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makale == null)
{
return HttpNotFound();
}
return View(makale);
}
// POST: AdminMakale/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
var makales = db.Makale.Where(m => m.MakaleId == id).SingleOrDefault();
if (makales == null)
{
return HttpNotFound();
}
if (System.IO.File.Exists(Server.MapPath(makales.Foto)))
{
System.IO.File.Delete(Server.MapPath(makales.Foto));
}
foreach (var i in makales.Yorum.ToList())
{
db.Yorum.Remove(i);
}
foreach (var i in makales.Etiket.ToList())
{
db.Etiket.Remove(i);
}
db.Makale.Remove(makales);
db.SaveChanges();
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
Try to use a DropDownListFor instead of a DropdownList. The error you mention means that you are having NULL in the SelectListItem. You should create a list of ListItem in the DropDownList.
(I'm not sure if I'm correct or not. I'm just trying to help quickly.)

Migrating to the WebApi 2.2 RC and getting Response Status 406 (not acceptable)

I migrated to the WebAPI 2.2 RC (Microsoft.AspNet.WebApi -Version 5.2.0-rc) and I since them I get only 406 (Not Acceptable) as status response on all my queries, for example:
http://localhost:7923/api/Quotes(1)
OData Service Configuration
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.EnableSystemDiagnosticsTracing();
config.MapODataServiceRoute("api", "api", CreateEdmModel());
}
private static IEdmModel CreateEdmModel()
{
var odataModelBuilder = new ODataConventionModelBuilder();
odataModelBuilder.EntitySet<Tag>("Tags");
odataModelBuilder.EntitySet<Author>("Authors");
EntitySetConfiguration<Quote> quoteEntitySetConfiguration = odataModelBuilder.EntitySet<Quote>("Quotes");
FunctionConfiguration getQuotesRandomFunction = quoteEntitySetConfiguration.EntityType.Collection.Function("Random");
getQuotesRandomFunction.Parameter<int>("count");
getQuotesRandomFunction.ReturnsCollectionFromEntitySet<Quote>("Quotes");
return odataModelBuilder.GetEdmModel();
}
}
QuotesController
public class QuotesController : ODataController
{
private WhatAQuoteDb db = new WhatAQuoteDb();
[ODataRoute("Default.Random(count={count})")]
[EnableQuery]
public IHttpActionResult GetQuotesRandom(int count)
{
return Ok(db.Quotes.OrderBy(quote => Guid.NewGuid()).Take(count));
}
// GET: odata/Quotes
[EnableQuery]
public IQueryable<Quote> GetQuotes()
{
return db.Quotes;
}
// GET: odata/Quotes(5)
[EnableQuery]
public SingleResult<Quote> GetQuote([FromODataUri] int key)
{
return SingleResult.Create(db.Quotes.Where(quote => quote.Id == key));
}
// PUT: odata/Quotes(5)
public async Task<IHttpActionResult> Put([FromODataUri] int key, Quote quote)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (key != quote.Id)
{
return BadRequest();
}
db.Entry(quote).State = EntityState.Modified;
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!QuoteExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(quote);
}
// POST: odata/Quotes
public async Task<IHttpActionResult> Post(Quote quote)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.Quotes.Add(quote);
await db.SaveChangesAsync();
return Created(quote);
}
// PATCH: odata/Quotes(5)
[AcceptVerbs("PATCH", "MERGE")]
public async Task<IHttpActionResult> Patch([FromODataUri] int key, Delta<Quote> patch)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
Quote quote = await db.Quotes.FindAsync(key);
if (quote == null)
{
return NotFound();
}
patch.Patch(quote);
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!QuoteExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(quote);
}
// DELETE: odata/Quotes(5)
public async Task<IHttpActionResult> Delete([FromODataUri] int key)
{
Quote quote = await db.Quotes.FindAsync(key);
if (quote == null)
{
return NotFound();
}
db.Quotes.Remove(quote);
await db.SaveChangesAsync();
return StatusCode(HttpStatusCode.NoContent);
}
// GET: odata/Quotes(5)/Author
[EnableQuery]
public SingleResult<Author> GetAuthor([FromODataUri] int key)
{
return SingleResult.Create(db.Quotes.Where(m => m.Id == key).Select(m => m.Author));
}
// GET: odata/Quotes(5)/Tags
[EnableQuery]
public IQueryable<Tag> GetTags([FromODataUri] int key)
{
return db.Quotes.Where(m => m.Id == key).SelectMany(m => m.Tags);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool QuoteExists(int key)
{
return db.Quotes.Count(e => e.Id == key) > 0;
}
}
I checked your solution and found that you used service reference.
However adding service reference doesn't support OData V4 and the version in your generated code is V3.
You can try OData T4 code generator to generate client code.
Check the blog below:
http://blogs.msdn.com/b/odatateam/archive/2014/03/11/how-to-use-odata-client-code-generator-to-generate-client-side-proxy-class.aspx
Update:
I checked your solution again and found the problem:
The ODataController you used is V3!
If you want the V4 version, you need to change the using namespace in your controller cs file
From
using System.Web.Http.OData;
To
using System.Web.OData;
What is more, there is other problem that the following template is invalid when I start up the project.
[ODataRoute("Default.Random(count={count})")]
I guest that the random function you defined is a function import and you should define like this:
FunctionConfiguration getQuotesRandomFunction = odataModelBuilder.Function("Random");
And the function import should not add namespace and the template should be:
[ODataRoute("Random(count={count})")]
Let me know if you have other problems.

The resource cannot be found Error

This error comes to me.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Dinner
I searched but there is not suitable answers for me.
The spell of my controller is correct. I tried and checked many times.
I did not customize my rounting Globle.asax
I checked the "Web" tab under my project's properties, the "SpecificPage is tickled without any contents"
Everything is by default. Anyway here is the default code for rounting. Who knows why?Thanks
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
Here is my Dinner controller
namespace NerdDinner.Controllers
{
public class DinnerController : Controller
{
IDinnerRepository _repository;
public DinnerController()
{
_repository = new sqlDinnerRepository();
}
public DinnerController(IDinnerRepository repository)
{
_repository = repository;
}
//
// GET: /Dinner/
public ActionResult Index()
{
var dinners = _repository.FindAllDinners();
return View(dinners);
}
//
// GET: /Dinner/Details/5
public ActionResult Details(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// GET: /Dinner/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Dinner/Create
[HttpPost]
public ActionResult Create(Dinner dinner)
{
try
{
// TODO: Add insert logic here
_repository.AddDinner(dinner);
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// GET: /Dinner/Edit/5
public ActionResult Edit(int id)
{
var dinner = _repository.GetDinner(id);
return View(dinner);
}
//
// POST: /Dinner/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
var dinner = _repository.GetDinner(id);
try
{
// TODO: Add update logic here
UpdateModel(dinner, collection.ToValueProvider());
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
//
// POST: /Dinner/Delete/5
[HttpPost]
public ActionResult Delete(int id)
{
var db = new dbDataContext();
var dinner = db.Dinners.SingleOrDefault(x => x.DinnerID == id);
try
{
// TODO: Add delete logic here
_repository.DeleteDinner(dinner);
_repository.UpdateDinner(dinner);
return RedirectToAction("Index");
}
catch
{
return View(dinner);
}
}
}
}
Here is IDinnerRepository interface
namespace NerdDinner.Models
{
interface IDinnerRepository
{
IQueryable<Dinner> FindAllDinners();
Dinner GetDinner(int id);
void AddDinner(Dinner dinner);
void UpdateDinner(Dinner dinner);
void DeleteDinner(Dinner dinner);
}
}
sqlDinnerRepository class implements IDinnerRepository interface
namespace NerdDinner.Models
{
public class sqlDinnerRepository
{
dbDataContext db;
public sqlDinnerRepository()
{
db = new dbDataContext();
}
public IQueryable<Dinner> FindAllDinners()
{
return db.Dinners;
}
public Dinner GetDinner(int id)
{
return db.Dinners.SingleOrDefault(x => x.DinnerID == id);
}
public void AddDinner(Dinner dinner)
{
db.Dinners.InsertOnSubmit(dinner);
}
public void UpdateDinner(Dinner dinner)
{
db.SubmitChanges();
}
public void DeleteDinner(Dinner dinner)
{
db.Dinners.DeleteOnSubmit(dinner);
}
}
}
I type "http://localhost:52372/Dinner" in my browser.

Route Constraint Isnt working for ASP.NET MVC

Why would the route http://localhost:2222/2012-adidas-spring-classic/37, not get picked up from the below route match? I get a 404 error.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*vti_inf}", new { vti_inf = #"(.*/)?_vti_inf.html(/.*)?" });
routes.IgnoreRoute("{*vti_rpc}", new { vti_rpc = #"(.*/)?_vti_rpc(/.*)?" });
#region API
routes.MapRouteLowercase(
"NamedHomeEvent",
"{year}-{name}/{Id}",
new { controller = "Event", action = "Index", year = DateTime.Now.Year },
new { year = #"\d{4}", Id = #"\d+" }
);
public virtual ActionResult Index(int? id, int? year, string name)
{
The routing engine cannot help you here. You could write a custom route to handle this case:
public class MyRoute : Route
{
public MyRoute()
: base(
"{year-name}/{id}",
new RouteValueDictionary(new { controller = "Event", action = "Index", id = UrlParameter.Optional }),
new RouteValueDictionary(new { id = #"\d*" }),
new MvcRouteHandler()
)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
var routeData = base.GetRouteData(httpContext);
if (routeData == null)
{
return null;
}
var yearName = (string)routeData.Values["year-name"];
if (string.IsNullOrWhiteSpace(yearName))
{
return null;
}
var parts = yearName.Split(new[] { '-' }, 2, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length < 2)
{
return null;
}
var year = parts.First();
int yearValue;
if (!int.TryParse(year, out yearValue))
{
return null;
}
var name = parts.Last();
routeData.Values.Add("year", year);
routeData.Values.Add("name", name);
return routeData;
}
}
and then register this route:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{*vti_inf}", new { vti_inf = #"(.*/)?_vti_inf.html(/.*)?" });
routes.IgnoreRoute("{*vti_rpc}", new { vti_rpc = #"(.*/)?_vti_rpc(/.*)?" });
routes.Add("NamedHomeEvent", new MyRoute());
}

Resources