Inconsistent accessibility: parameter type is less accessible - asp.net-mvc

public class UserController : Controller
{
//
// GET: /User/
public ActionResult Register()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(User U)
{
if (ModelState.IsValid)
{
using (MyDatabaseEntities dc = new MyDatabaseEntities())
{
dc.Users.Add(U);
dc.SaveChanges();
ModelState.Clear();
U = null;
ViewBag.Message = "Successfully register Done";
}
}
return View(U);
}
}

I suspect, but without the full error message giving us the type and location in the code it is something of a guess, that type User is protected or internal.

Related

Return Action as result of another action?

public ActionResult Index(int requestid)
{
return View(db.RequestListDetails.Where(c=>c.RequestID == requestid).ToList());
}
How can I back to View(db.RequestListDetails.Where(c=>c.RequestID == requestid).ToList()); from Create action.
My Create action code like this
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "....")] RequestListDetail requestListDetail)
{
if (ModelState.IsValid)
{
db.RequestListDetails.Add(requestListDetail);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(requestListDetail);
}
After db.SaveChanges() you could use this:
return RedirectToAction("Index", new { requestid = requestListDetail.RequestId });

MVC HTTP Error 403.14 - Forbidden after create new record

1- AuthorizeUserAttribute.cs is class for costume authorize attribute
public class AuthorizeUserAttribute : AuthorizeAttribute
{
public string AccessLevel { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = base.AuthorizeCore(httpContext);
if (!isAuthorized)
return false;
if (this.AccessLevel.Contains("Admin"))
{
return true;
}
else return false;
}
2- this is my controller
[AuthorizeUser(AccessLevel = "Admin")]
public class ProductsController : Controller
{
private DataBaseContext db = new DataBaseContext();
public ActionResult Index()
{
var product = db.Product.Include(p => p.ProductGroup);
return View(product.ToList());
}
}
[AuthorizeUser(AccessLevel = "Admin")]
public ActionResult Create([Bind(Include = "Product_Id,ProductName,Description,PicUrl,Group_Id")] Product product)
{
if (ModelState.IsValid)
{
db.Product.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.Group_Id = new SelectList(db.ProductGroups, "Group_Id", "GreoupName", product.Group_Id);
return View(product);
}
3-FilterConfig.cs in start_up folder
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
filters.Add(new AuthorizeUserAttribute());
}
}
4-Global.asax.cs
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
5- Admin1Controller.cs for login and etc...
[HttpPost]
public ActionResult Login(LoginViewModel model)
{
if (!ModelState.IsValid) //Checks if input fields have the correct format
{
return View(model); //Returns the view with the input values so that the user doesn't have to retype again
}
if(model.Email == "info#psmgroups.com" & model.Password == "#1234psm")
{
var identity = new ClaimsIdentity(new[] {
new Claim(ClaimTypes.Name,"Admin" ),
new Claim(ClaimTypes.Email, "info#psmgroups.com"),
new Claim(ClaimTypes.Role,"Admin")
}, "ApplicationCookie");
var ctx = Request.GetOwinContext();
var authManager = ctx.Authentication;
authManager.SignIn(identity);
return Redirect(GetRedirectUrl(model.ReturnUrl));
}
ModelState.AddModelError("", "incorrect UserName or pass");
return View(model);
}
after create new product and return to products/ show HTTP Error 403.14 - Forbidden page. while write product/Index show correct page
First, there's no code here that actually ever sets the AccessLevel property on your custom attribute. Maybe you just didn't post it, but if this is all your code, then it's fairly obvious why this doesn't work: AccessLevel is always null, and therefore never contains the string "Admin".
That said, you don't even need a custom attribute here. AuthorizeAttribute already handles roles. It seems you're trying to implement some sort of parallel role-like functionality, but that's a waste of time. Just do:
[Authorize(Roles = "Admin")]
And call it a day.

How "Don't Repeat Yourself" in methods of a Controller in ASP.NET MVC?

within each methods of a controller , I have to execute a method.
public ActionResult Index1()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index1();
return View();
}
public ActionResult Index2()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index2();
return View();
}
public ActionResult Index3()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index3();
return View();
}
public ActionResult Index4()
{
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Code4Index4();
return View();
}
Is there a smarter way than organize the code or I am forced to go against DRY concept?
I'd like not repeat the code for each method :
if (Foo(id, SessionManage.DataSession) )
return RedirectToAction("Page1");
Thanks to all.
Well, ASPNET has already the infrastructure for handling authorization so why not just use it?
Create a new attribute class, inherited from AuthorizeAttribute
Override the methods:
OnAuthorization: to perform your check
HandleUnauthorizedRequest: to decide whats the result view that the user will see.
Mark your controller methods with this attribute.
Your attribute may look like:
class MyCustomAuthorizeAttribute : AuthorizeAttribute
{
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// Do whatever you want here, for example
//filterContext.Result = new whatever() ;
base.HandleUnauthorizedRequest(filterContext);
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if ( /* the request does not pass your checks */ )
throw new UnauthorizedAccessException();
}
}
And your controller code will look like:
[MyCustomAuthorize]
public ActionResult Index1()
{
return View();
}
[MyCustomAuthorize]
public ActionResult Index2()
{
return View();
}
[MyCustomAuthorize]
public ActionResult Index3()
{
return View();
}
[MyCustomAuthorize]
public ActionResult Index4()
{
return View();
}
You can also check this post for a more clear example:
https://stackoverflow.com/a/5663518/1413973
You can refactor your controller like this:
public ActionResult Index1()
{
return AccessDeniedRedirect();
}
public ActionResult Index2()
{
return AccessDeniedRedirect();
}
public ActionResult Index3()
{
return AccessDeniedRedirect();
}
public ActionResult Index4()
{
return AccessDeniedRedirect();
}
private ActionResult AccessDeniedRedirect()
{
if (Checks(id, SessionManage.DataSession))
return RedirectToAction("AccesDiened");
return View();
}

Custom Authentication for different areas in mvc

I have a MVC project with 2 areas: Admin and Client. I also have a login page in the main controller. What I want to do is to Authenticate a user based on its roles. If the user is for client they can't login to admin and the other way around.
For example if you try Localhost/admin, the code checks if the user is authorised. If not it redirects you to Localhost/admin/AccountLogin. The same for Localhost/client to Localhost/client/account/login.
I want to use a customAuthorize rather than [Authorize(Roles="Admin")].
everything works fine if I don't use roles, but the problem is if you login as client you can simply change the url and go to admin. So I tried to use roles.
In admin area:
An account Controller:
public class AccountController : MainProject.Controllers.AccountController
{ }
A home controller:
[CustomAuthorize("Admin")]
public class HomeController : Controller
{
public ActionResult HomePage()
{
return View();
}
}
The custom Authorise:
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
private string _loginPage { get; set; }
private string _customRole { get; set; }
public CustomAuthorizeAttribute(string userProfilesRequired)
{
_customRole = userProfilesRequired;
_loginPage = "/" + _customRole + "/Account/Login";
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
var formsIdentity = filterContext.HttpContext.User.Identity as System.Web.Security.FormsIdentity;
// I want to check if the role of current user is the same as the controller If not redirect to the /account/login page.
var validRole = this.Roles == _customRole;//filterContext.HttpContext.User.IsInRole(_customRole);
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
if (!validRole)
{
filterContext.HttpContext.Response.Redirect(_loginPage);
}
}
else
{
filterContext.HttpContext.Response.Redirect(_loginPage);
}
base.OnAuthorization(filterContext);
}
}
The Account Controller in Main Controller:
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Login()
{
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string ReturnUrl)
{
try
{
if (ModelState.IsValid)
{
if (model.UserName == "Arash" && model.Password == "123")
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
//I need to set the roles here but not sure how
return RedirectToAction("homePage", "Home", new { area = GetArea() });
}
}
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
catch (Exception ex)
{
ModelState.AddModelError("", "Error: " + ex.Message);
return View(model);
}
}
}
and it the web config:
<forms loginUrl="~/Account/Login" timeout="200" />
</authentication>
<authorization>
<allow roles="Admin,Client" />
</authorization>
I searched a lot in the web but couldn't find a proper answer. I appreciate if you Could help me out to correctly implement this authorisation in MVC.
I just want to know how can I set a role to a user when login. At the moment if I set a user in login, it can't remember when it gets to CustomAuthorize class.
Any help?
Cheers,
There are a lot of ways to this but I will tell you what I used in this case.
You don't actually need to create a custom Authorization Attribute but instead make use of PostAuthenticateRequest event Handler in Global.asax given that you have a "table" roles in your database.
Add the code below in Global.asax
public override void Init()
{
this.PostAuthenticateRequest += new EventHandler(MvcApplication_PostAuthenticateRequest);
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
if (User.Identity.IsAuthenticated && User.Identity.AuthenticationType == "Forms")
{
string[] roles = GetRoleOfUser(Context.User.Identity.Name);
var newUser = new GenericPrincipal(Context.User.Identity, roles);
Context.User = Thread.CurrentPrincipal = newUser;
}
}
public string[] GetRoleOfUser(string username)
{
string[] usersInRole;
// Get the Role of User from the Database
// Should be of String Array
// Example Query to Database: 'Select UserRole FROM User WHERE Username = "arash"'
// It doesnt matter if user has One or more Role.
return usersInRole;
}
Then your account controller should be this.
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login(LoginModel model, string ReturnUrl)
{
try
{
if (ModelState.IsValid)
{
if (model.UserName == "Arash" && model.Password == "123")
{
FormsAuthentication.SetAuthCookie(model.UserName, false);
HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
return RedirectToAction("HomePage", "Home");
}
}
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
catch (Exception ex)
{
ModelState.AddModelError("", "Error: " + ex.Message);
return View(model);
}
}
Now for example there is an Action in your HomeController that can only be access by Admin. You can just decorate the action with Authorize attribute like this below.
HomeController.cs
[Authorize(Roles = "Admin")]
public ActionResult AdminHomepage()
{
//For Admin Only
return View();
}
[Authorize(Roles = "Client")]
public ActionResult ClientHomepage()
{
//Client only Homepage, User with Role "Admin" cant go here.
return View();
}
[AllowAnonymous]
public ActionResult HomePageForAll()
{
//For Everyone
return View();
}
[Authorize(Roles = "Client,Admin")]
public ActionResult HomePageForClientAndAdmin()
{
return View();
}
public ActionResult HomePage()
{
return View();
}
The user will be redirected to Login URL if they are not authorized given that it is specified in Web.config (Which you already have set).
I have an action method and that can be accessed by Admin only
// Action Methods
[AuthorizationService] // My custom filter ,you can apply at controller level
public ActionResult ProjectList(Employee emp)
{
// do some work
}
//Employee class
public class Employee
{
string Name{get;set;}
string Role{get;set;}
}
// My custom filter
class AuthorizationService : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Employee = filterContext.ActionParameters["emp"] as Employee;
if (Employee.Role!="Admin")
{
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new { action = "Login", Controller ="Home"}));
}
}
}

Validation error about Decimal data type in asp.net mvc

I defined a data type decimal(18,10) for longitute and latitute in my database. But it always said "validation error" when I tried to input and submit my form.
I used LINQ to SQL. Is there some validation rules it generated for me otherwise why I can not input these two with something numbers like "2.34".
Thanks in advance
namespace Nerddinner.Models
{
interface IDinnerRepository
{
IQueryable<Dinner> FindAllDinners();
Dinner GetDinner(int id);
void AddDinner(Dinner dinner);
void UpdateDinner(Dinner dinner);
void DeleteDinner(Dinner dinner);
}
}
namespace Nerddinner.Models
{
public class sqlDinnerRepository: IDinnerRepository
{
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);
}
}
}
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 db = new dbDataContext();
var dinner = db.Dinners.SingleOrDefault(x => x.DinnerID == 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);
}
}
}
}
Thanks for helping me.
In ASP.NET MVC, You can use the DisplayFormatAttribute on your model property:
[DisplayFormat(DataFormatString = "{0:0.##}")]
public decimal decimalNumber { get; set; }
The above will output a number with up to 2 decimal places.
For more information visit: Custom Numeric Format Strings and Standard Numeric Format Strings
IN SQL SERVER:
*decimal(m,a)*: m is the number of total digits your decimal can have, while a is the max number of decimal points you can have.
so if you put PI into a Decimal(18,0) it will be recorded as 3
if you put PI into a decimal(18,2) it will be recorded as 3.14
if you put PI into Decimal(18,10) be recorded as 3.1415926535
I think my answer will help you. Correct me if I am wrong.

Resources