asp.net-mvc-4 - 如果用户尝试通过 URL 访问其他网站页面,如何在 C# MVC 4.5 中重定向已登录或未登录到登录页面的用户

标签 asp.net-mvc-4 session c#-4.0

我有一个网站,我希望用户在未登录的情况下被重定向到“登录”页面。用户可以尝试通过发布网址来访问该网页。我想在 C# MVC 4.5 中执行此操作

在这里,除非登录,否则我不希望“[授权]”操作可用。 查看索引页是索引操作。

  //Login Controller
  [AllowAnonymous]
  public ActionResult Index()
  {
      return View();
  }
  [HttpPost]
   public ActionResult Index(FormCollection frm)
    {
        ....//other code
    }

 [Authorize]
 public ActionResult Index()
    {
        List<DTO> obj = objConfigurator.GetDataList();
        return View(obj);
    }


    public ActionResult Edit(int Id)
    {
        DTO obj = objC.GetListById(Id);
        return View(obj);
    }

最佳答案

使用 Controller 上的[Authorize]属性。

[Authorize] 
public class YourController: Controller
{
 . . .
    [AllowAnonymous]
    public ActionResult Register()
    {
    }

    [AllowAnonymous]
    public ActionResult LogIn()
    {
    }
. . .
} 

此外,您必须在 web.config 中添加登录页面 -

<system.web>
    <authentication mode="Forms">
      <forms loginUrl="~/Login" timeout="2880" />
    </authentication>
</system.web>

您还有另一个甚至更好的选择,将 AuthorizeAttribute 注册为 global.asax 文件中的全局过滤器。

public static void RegisterGlobalFilters(GlobalFilterCollection filters)

{
    ....
    filters.Add(new System.Web.Mvc.AuthorizeAttribute());
}

这样,您只需将[AllowAnonymous]应用于您希望匿名用户访问的操作。

关于asp.net-mvc-4 - 如果用户尝试通过 URL 访问其他网站页面,如何在 C# MVC 4.5 中重定向已登录或未登录到登录页面的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28825324/

相关文章:

javascript - ASP.Net MVC 模型绑定(bind)到 javascript

java - apache commons httpclient 4.23表单登录问题不同请求中使用不同的 session cookie

asp.net - ASP.Net 中的客户端 session 超时重定向

c#-4.0 - 如何强制 Entity Framework 不要查询为 sp_executesql

c# - 全选文本框文本

javascript - 来自 Controller 的警报消息 : Add alert behavior in partial view?

c# - ExpertPdf 转换错误 : WebKit Navigation timeout in GetPdfBytesFromUrl

session - Beego Session 不自动向模板传递数据

c# - asp.net mvc c#中的Json序列化

c# - 通过Ajax方法发送文本到 Controller