0

I'm working on asp.net mvc webapi which returns result in json format. I'm trying to set the Response.StatusCode in which I'm partially succeed. When I hit the API on localhost with Postman it returns the status code and error message which I have set manually, but when I hit the API using published link it returns only StatusCode.

public JsonResult Demo(string Fordate)
{ 
    if (string.IsNullOrEmpty(Fordate))
    {
        errorMsg = "For Date is invalid, please correct";
        ControllerContext.HttpContext.Response.StatusCode = Convert.ToInt32(HttpStatusCode.Unauthorized); 
        return Json(new { Response = errorMsg }, JsonRequestBehavior.AllowGet);
    }
}

When I run above code on localhost using Postman it gives following output which is expected output:

But when I tried it with my published link it displays below Output in Postman:

There is No error message which set manually

I have tried following line of code also but it does not work if there is a try-catch block. If I put this line of code in try-catch block it gives the error:

Cannot use local variable 'Response' before it is declared

Response.StatusCode = Convert.ToInt32(HttpStatusCode.Forbidden);
return Json(new { Response.StatusCode, Response = error }, JsonRequestBehavior.AllowGet);
Alex
  • 2,931
  • 6
  • 15
  • 35

2 Answers2

1

Your error message clearly says that unauthorized access is denied due to invalid credentials. Read this article as this explains clearly.

https://support.microsoft.com/en-in/help/871179/you-receive-an-http-error-401-1-unauthorized-access-is-denied-due-to-i

Thameem
  • 537
  • 7
  • 24
0

This happens because the 401 error is a server error. As such, the request never reaches your GET action.

Does your controller have the [Authorize] attribute? If so, you can replace it with a custom attribute (recommended) as described here or just remove it and let your action handle it (not recommended):

throw new HttpResponseException(HttpStatusCode.Unauthorized);

An even better solution, if you are using .NET Core, might be to configure your Startup.cs class like so (you may need to configure this to your liking):

services.AddIdentity<User, IdentityRole>(options =>
{
    options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
    {
        OnRedirectToLogin = ctx =>
        {
           if (ctx.Request.Path.StartsWithSegments("/api") &&
               ctx.Response.StatusCode == (int) HttpStatusCode.OK)
           {
               ctx.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
           }
           else
           {
               ctx.Response.Redirect(ctx.RedirectUri);
           }
           return Task.FromResult(0);
        }
    };
});

Ref. https://devblog.dymel.pl/2016/07/07/return-401-unauthorized-from-asp-net-core-api/

In later versions of .NET Core (and Identity) you may want to use something like this (again, you will want to customize this to suit your requirements):

services.ConfigureApplicationCookie(options =>
{
    options.LoginPath = new PathString("/Account/Login");
    options.LogoutPath = new PathString("/Account/Logout");

    options.Events.OnRedirectToLogin = context =>
    {
        if (context.Request.Path.StartsWithSegments("/api")
            && context.Response.StatusCode == StatusCodes.Status200OK)
        {
            context.Response.Clear();
            context.Response.StatusCode = StatusCodes.Status401Unauthorized;
            return Task.FromResult<object>(null);
        }
        context.Response.Redirect(context.RedirectUri);
        return Task.FromResult<object>(null);
    };
});

Ref. https://stackoverflow.com/a/47240601/1477388

user1477388
  • 19,139
  • 26
  • 125
  • 240
  • My controller does not have the [Authorize] attribute And I'm not using .NET Core.How can I display My error message which I'm manually setting with those StatusCode as I have to display the error message also with statuscode – Suchir Patel Jul 30 '19 at 05:39
  • What versions of .NET, MVC and Identity are you using? You can find these answers in the References folder of your solution under Solution Explorer. Right-click each dependency and select "Properties" to find the version. – user1477388 Jul 30 '19 at 12:57