加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-4 – 如果用户尝试通过URL访问其他网站页面,如何在C

发布时间:2020-12-16 03:17:17 所属栏目:asp.Net 来源:网络整理
导读:我有一个网站,如果他们没有登录,我希望用户被重定向到“登录”页面.用户可以尝试通过发布网址来访问网页.我想在C#MVC 4.5中做到这一点 除非已登录,否则我不希望“[授权]”操作可用. 它是查看索引页面的索引操作. //Login Controller [AllowAnonymous] public
我有一个网站,如果他们没有登录,我希望用户被重定向到“登录”页面.用户可以尝试通过发布网址来访问网页.我想在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);
    }

解决方法

使用控制器上的[授权]属性.

[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>

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

public static void RegisterGlobalFilters(GlobalFilterCollection filters)

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

这样,您只需将[AllowAnonymous]应用于您希望被无用用户访问的操作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读