securing a string method - controller
I return "~/Error/Unauthorized" page if a user is not admin and tries to access certain controllers. Here is how I return the error page:
if (!Models.Authorization.AdminPageCheck(this.User))
return 开发者_如何学编程new RedirectResult("~/Error/Unauthorized");
I am able to do it for ActionResult methods, but not for string methods as it doesn't return a view. How can I secure a string method?
It's preferable to use ASP.NET MVC's built-in capability, and just annotate your Controller (either at the class level, for all actions, or at the action method level) with
[Authorize]
In the event that someone tries to call a method and they are not logged in, they'll be forced to authenticate using the method configured in web.config.
Or, if you use
[Authorize(Roles = "AdminRole")]
They'll be forced to authenticate, if they're not already, then they'll be granted or denied access based on them having the relevant role.
It's a very common requirement and thankfully, the ASP.NET MVC Team have dealt with it very comprehensively!
You should change those methods to return ActionResult
s.
You can then return Content(someText, "content/type")
If you sometimes have a different outcome than just a string, then the preferred "fix" there would be: don't return string
; return ActionResult
, and when it is the string,
return Content(yourString);
Optionally specifying a content-type / encoding.
As SLaks mentioned, you can change the return type of the string methods to ActionResult, then use the ContentResult class to return a string.
精彩评论