Returning 'other than HTML' formatted errors for AJAX calls to Web API

Investigating the Web API as part of an MVC 4 project as an alternative way to provide an AJAX-based API. I've extended AuthorizeAttribute for the MVC controllers such that, if an AJAX request is detected, a JSON-formatted error is returned. The Web API returns errors as HTML. Here's the AuthorizeAttribute that I'm using with the MVC controllers:

public class AuthorizeAttribute: System.Web.Mvc.AuthorizeAttribute
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)

        filterContext.Result = new RedirectToRouteResult(
            new RouteValueDictionary 
                { "area", "" },
                { "controller", "Error" },
                { "action", ( filterContext.HttpContext.Request.IsAjaxRequest() ? "JsonHttp" : "Http" ) },
                { "id", "401" },

How could I reproduce this to provide equivalent functionality for the Web API?

I realize that I need to extend System.Web.Http.AuthorizeAttribute instead of System.Web.Mvc.AuthorizeAttribute but this uses an HttpActionContext rather than an AuthorizationContext and so I'm stuck by my limited knowledge of the Web API and the seemingly incomplete documentation on MSDN.

Am I even correct in thinking that this would be the correct approach?

Would appreciate any guidance.


To get the equivalent functionality in a Web API filter you can set the HttpActionContext.Response property to an instance of HttpResponseMessage that has the right redirect status code and location header:

protected override void HandleUnauthorizedRequest(HttpActionContext actionContext) {
    var response = new HttpResponseMessage(HttpStatusCode.Redirect);
    response.Headers.Location = new Uri("my new location");
    actionContext.Response = response;

Need Your Help

PHPUnit and Mock Objects not working

php object mocking phpunit stubs

I am not sure if I am doing something wrong or it is a bug with PHPUnit and mock objects. Basically I am trying to test if $Model->doSomething() is called when $Model->start() is triggered.

How to convert control.background(brush) to bitmap?

c# wpf bitmap brush

How to convert to bitmap?Thanks.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.