I'm doing a simple user signup web project. Whenever I add the [Authorize] in the controller and subsequently created the view from it, when I run the code, it produced HTTPS 401.0 Unauthorized Error. If I removed it, it runs, but not producing the result I wanted exactly.
In my Account Controller
, I had this:
[HttpPost]
public ActionResult SignUp(UserSignUpView USV)
{
if (ModelState.IsValid)
{
UserManager UM = new UserManager();
if (!UM.IsLoginNameExist(USV.LoginName))
{
UM.AddUserAccount(USV);
FormsAuthentication.SetAuthCookie(USV.FirstName, false);
return RedirectToAction("Welcome", "Home");
}
else ModelState.AddModelError("", "Login Name already taken.");
}
return View();
}
In my Home
controller, I had this:
namespace MVC5FileRealWorld.Controllers
{
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[Authorize]
public ActionResult Welcome()
{
return View();
}
}
}
I created a view by add view from right click the Welcome()
Below is my Welcome
class:
@{
ViewBag.Title = "Welcome";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Hi <b>@Context.User.Identity.Name</b>! Welcome to my first MVC 5 Web App!</h2>
After the user successfully registered (ie data successfully saved into the database),
It should display 'Hi XXX! Welcome to my first MVC5 Web App!'
But now if I added [Authorize] and generate a view, then it will just display the HTTP 401.0 error. If I removed [Authorize] and regenerate another view (the same name as previous one), it will just display 'Hi. Welcome to my first MVC5 Web App!'. This line of code @Context.User.Identity.Name
just doesn't seem to work also for the latter case.
You get the 401 when you're not authorized while trying to access a "protected" resource.
If you're not authorized: @Context.User.Identity.Name
will return an empty string.
So far, this is what you are experiencing.
You show the code of "SignUp", which creates a authentication cookie, which should authorize the user. Next to that; you should have a "log in" form on which a user can log in.
So, login with an existing user, or signup with a new one. If tho cookie persists you'll be authorized.
As a last resort you can try:
FormsAuthentication.SetAuthCookie(USV.FirstName, true);
or maybe you need to check your web.config
<authentication mode="Forms"> <forms loginUrl="..." cookieless="UseCookies" /> </authentication> <!-- more stuff --> <modules> <!-- removed module --> <!--<remove name="FormsAuthenticationModule" />--> </modules>
see: FormsAuthentication.SetAuthCookie doesn't [Authorize] in MVC 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.