views:

82

answers:

2

I have a .NET MVC controller action that returns a JsonResult to a YUI AsyncRequest callback. All is working fine with the AsyncRequest call and the "Content" model data is successfully updated. How can I now assure that the user is logged before the AsyncRequest is made?

Normally I would use the [Authorize] attribute which returns an error back to my YUI AsyncRequest since it is expecting a Json result.

I've also tried checking "User.Identity.IsAuthenticated" wihtin the Action but still no love.. The RedirectToRoute seems to do nothing.

I have been able to send a Json result back to JS that indicated the user needs to login, but I'd rather have it redirect the user to the LogOn view.

Here is the Controller action:

[JsonFilter(Param="content"), JsonDataType=typeof(Content)]
public ActionResult SaveJson(Content content) 
{

    if (!User.Identity.IsAuthenticated)
     RedirectToRoute(new { Action="LogOn", Controller="Account"});


    contentRepository.Update(content);
    return Json(new {Result = "sucess"});

}

TIA!

+1  A: 

You can do something like:

[JsonFilter(Param="content"), JsonDataType=typeof(Content)]
public ActionResult SaveJson(Content content) 
{

    if (!User.Identity.IsAuthenticated)
    {
        var urlHelper = new UrlHelper(ControllerContext.RequestContext);
        return Json(new {Result = "unauthenticated" , Url = urlHelper.Action("LogOn", "Account")});
    }

    contentRepository.Update(content);
    return Json(new {Result = "sucess"});
}

You will use urlHelper.Action("LogOn", "Account") part of result to change location to login page (window.location.href = ...).

Additional note: You can move urlHelper.Action("LogOn", "Account") to your view, as a part of your callback function.

LukLed
Thanks.. I started to think about using window.location in my JS, and I like your idea of passing the url back to it,
Skelly
@Skelly: Remember that you don't have to pass it, you can already have it during view generation and that is propably more preferred way.
LukLed
A: 

I think the semantically correct thing to do is return an HTTP response with a 401 (Unauthorized) status code and let the js decide how to respond. I'm not familiar with YUI, but in jQuery you can setup an error callback function like so...

function BasicJSONPost(urlToPost, dataToSend, onSuccess) {
$.ajax({
    url: urlToPost,
    data: dataToSend,
    dataType: "json",
    type: "POST",
    success: onSuccess,
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        HandleAjaxError(XMLHttpRequest, textStatus, errorThrown);
    }
});
}

function HandleAjaxError(XMLHttpRequest, textStatus, errorThrown) {
    if (XMLHttpRequest.status == 401) {
        window.location.href = '/account/login';
    }
}
Jace Rhea