ASP MVC5部分视图身份验证重定向

时间:2015-06-05 16:28:06

标签: c# asp.net asp.net-mvc redirect partial-views

我对ASP很新,所以要宽容:)

我有一个带有搜索表单的视图。

查看

<div id="search-form" class="row search-form">
    @using(Ajax.BeginForm("Search",
    "Home",
    new AjaxOptions
    {
        UpdateTargetId = "result",
        InsertionMode = InsertionMode.Replace,
        LoadingElementId = "ajax_loader"
    },
    new { @class = "form-horizontal col-sm-offset-3 col-sm-6" }
    ))
    {
        <div class="form-group">
            <div class="col-sm-10">
                @{string query = string.Empty;}
                @Html.EditorFor(x => query, new { htmlAttributes = new { @class = "form-control" } })
            </div>
            <input id="submitbtn" type="submit" value="Search" class="btn btn-primary col-sm-2" />
        </div>
    }
</div>

<div id="ajax_loader" style="display:none">
    <img src="~/Content/Images/ajax_loader.gif" alt="Ajax Loader" />
</div>
<div id="result"></div>

控制器

[AllowAnonymous]
public ActionResult Index()
{
   ViewBag.Title = "serach form";
   return View();
}

public async Task<ActionResult> Search(string query)
{
   WinesApiController winesCtrl = new WinesApiController();
   var listOfWines = await winesCtrl.Get(query);
   return PartialView("_WineResult", listOfWines);
}

我的控制器中的Search方法返回一个PartialView。当我使用[AllowAnonymous]属性装饰控制器中的所有方法时,一切都运行良好。但我希望它能为任何人显示表单,但只要你点击搜索按钮,你就需要登录。所以我删除了所有的AllowAnonymous属性,但是在Index方法(渲染我的View的方法)上)。现在,我的呼叫结果不再显示(这很好),但我没有重定向到登录视图。

我的问题是,为什么调用局部视图不会将我重定向到登录视图?我想执行身份验证是因为我看不到提交操作的结果,但为什么我没有重定向呢?

2 个答案:

答案 0 :(得分:0)

您正在对搜索操作进行ajax调用吗?当ajax调用授权失败时,默认的asp.net mvc AuthorizeAttribute不会返回适当的响应。 您可以编写自己的授权过滤器,返回更好的响应,如下所示:

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public sealed class YourAuthorizeAttribute : AuthorizeAttribute {

    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {

        var httpContext = filterContext.HttpContext;
        var request = httpContext.Request;
        var response = httpContext.Response;

        if (request.IsAjaxRequest()) {
            response.SuppressFormsAuthenticationRedirect = true;
            response.StatusCode = (int)HttpStatusCode.Unauthorized;
            response.End();
        }

        base.HandleUnauthorizedRequest(filterContext);
    }
}

使用此过滤器,您可以使用默认的javascript代码来处理所有未经授权的方案:

$.ajaxSetup({
    statusCode: {
        401: function (response) {
            var returnUrl = encodeURI(window.location.pathname + window.location.search);
            var loginUrl = '/custumer/login?ReturnUrl=' + returnUrl;

            window.location.href = loginUrl;
        }
    }
});

答案 1 :(得分:-1)

如果您对操作设置了Authorize属性会怎样?

[Authorize()]
public async Task<ActionResult> Search(string query)
{
   WinesApiController winesCtrl = new WinesApiController();
   var listOfWines = await winesCtrl.Get(query);
   return PartialView("_WineResult", listOfWines);
}