2011-09-23 37 views
0

我试图在我的MVC3站点中建议类似this article的建议。但是,我不确定我可以在Action中使用Response.End。Response.End在MVC3 Action中的使用

我的问题是,如果HttpContext.User == null,我该如何从我的Action返回一个401状态码?

public ActionResult WinUserLogOn(string returnUrl) { 
     var userName = string.Empty; 

     if (HttpContext.User == null) { 
      //This will force the client's browser to provide credentials 
      Response.StatusCode = 401; 
      Response.StatusDescription = "Unauthorized"; 
      Response.End(); 
      return View("LogOn"); //<== ???? 
     } 
     else { 
      //Attempt to Log this user against Forms Authentication 
     } 
+0

您发布的代码似乎有问题? – vcsjones

+0

我假设我的响应代码和描述将在覆盖视图返回时被覆盖。 –

+0

虽然m.edmondson对他的回答是正确的,但是Response.End()会将所有内容全部清除并杀死线程,因此,在Response.End后执行的操作并不重要,除非通过' 。这不像答案提供的那样清楚。 – vcsjones

回答

5

这应该做你想要什么:

return new HttpUnauthorizedResult(); 

将一个HTTP 401返回到浏览器。 See the docs

+1

+1。 Response.End没有必要。 – StriplingWarrior

+0

虽然这工作,我不能像文章建议的东西工作。基本上所有发生的情况是,网站会重定向到LogOn页面,因为它应该在用户未通过身份验证时进行。我想这个解决方案不适用于MVC。 –