I have the following asp.net web api method to delete a file:
[Authorize]
[HttpPost]
public IHttpActionResult Delete(int id)
{
var uploadedFile = unitOfWork.FileRepository.Get(id);
if (uploadedFile == null)
return NotFound();
if (uploadedFile.CreatedBy != User.Identity.GetUserId())
return Unauthorized();
unitOfWork.FileRepository.Remove(uploadedFile);
unitOfWork.Complete();
return Ok();
}
I want to return an unauthorized result if the user attempting to delete the file did not create the file. I have the following ajax to handle the call but upon testing I always get response 200 and so the fail function never get called in my ajax function?
I have debugged the web api method with break points and it clearly fires the Unauthorized method - return Unauthorized();
So why is it returning status 200 when i view in firefox console:
POST http://localhost:65179/api/file/2 200 OK 29ms
When i check the response header in console it shows the following:
X-Responded-JSON {"status":401,"headers":{"location":"http:\/\/localhost:65179\/Account\/Login?ReturnUrl=%2Fapi%2Ffile%2F94"}}
So im at a loss as to why the fail function is not being called? I thinks it's doing a redirect to the login page hence the status is being returned as 200. How do i suppress the redirect then?
function () {
$.ajax({
url: "api/file/2",
method: "POST"
})
.done(function () {
alert("File has been deleted.");
})
.fail(function ( jqXHR) {
alert("Unable to delete file");
});
});
*** UPDATE ****
I've found the following blog post as a potential solution but it will only work if your project is only web api.
My project is a combination of MVC 5 and web api 2 so I've amended it and added the code to startup.auth.cs as follows but I've had to comment out the OnValidateIdentity bit inorder to add the OnApplyRedirect to the cookieoptions.
public void ConfigureAuth(IAppBuilder app)
{
var cookieOptions = new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
// Enables the application to validate the security stamp when the user logs in.
// This is a security feature which is used when you change a password or add an external login to your account.
//OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
// validateInterval: TimeSpan.FromMinutes(30),
// regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
OnApplyRedirect = ctx =>
{
if (!IsApiRequest(ctx.Request))
{
ctx.Response.Redirect(ctx.RedirectUri);
}
}
}
};
app.UseCookieAuthentication(cookieOptions);
}
private static bool IsApiRequest(IOwinRequest request)
{
string apiPath = VirtualPathUtility.ToAbsolute("~/api/");
return request.Uri.LocalPath.StartsWith(apiPath);
}
.fail()is a jqXHR, It has status propertyForbidden (403)rather thanUnauthorized (401)which is more meaningful -return new HttpResponseMessage(HttpStatusCode.Forbidden)? en.wikipedia.org/wiki/…. - Not sure whether the middleware will handle 403 as well though..