ASP.NET MVC5 removes html response for API errors

I would like to know how best to solve this problem.

The application has mvc web and web api. I have a separate mvc web controller (called Error) responsible for displaying error pages. My web.config looks like this:

<system.webServer>  
    <httpErrors errorMode="Custom" existingResponse="Replace">
      <remove statusCode="404" />
      <remove statusCode="500" />
      <error statusCode="404" responseMode="ExecuteURL" path="/error/404" />
      <error statusCode="500" responseMode="ExecuteURL" path="/error/500/" />
    </httpErrors>
</system.webServer>

It works for mvc web pages, but for web api now, when I return NotFound (), I get html error pages in response. I decided to fix this using the location attribute:

<location path="api">
    <system.webServer>
      <httpErrors errorMode="Custom" existingResponse="Replace">
        <remove statusCode="404" />
        <remove statusCode="500" />
      </httpErrors>
    </system.webServer>
</location>

So now it does not return html, but just an error string from asp.net.

But what if I need to return some object from the web api and just set the error header in action, for example, or just the error header without data?

thanks

+4
2

, , , (json) , . , , , !

, .

api web.config

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" />
  <remove statusCode="500" />
  <error statusCode="404" responseMode="File" path="templates\404.json" />
  <error statusCode="500" responseMode="File" path="templates\500.json" />
</httpErrors>

500.json \templates

{
    "Code": 500,
    "Message":  "Something went wrong, please try again later" 
}

(http status code 500)

500 Error in the API

. iisreset.


2 -

API, json . //.

public class ApiExceptionAttribute : ExceptionFilterAttribute 
{
    string _message = null;

    public ApiExceptionAttribute(string exceptionMessage = null) //to add custom message
    {
        _message = exceptionMessage;
    }

    public override void OnException(HttpActionExecutedContext context)
    {
        var message = new { 
            ExceptionType = "Custom", //or some other detail
            Message = _message == null ? "Something went wrong, please try later" : _message 
        };
        context.Response = context.Request.CreateResponse(HttpStatusCode.SeeOther, message, "application/json");
    }
}

API ( )

[ApiExceptionAttribute("This end point is to test error!")]
public class TestController : ApiController
{
    public IEnumerable<string> Get()
    {
        //actual code here
        throw new Exception("Back-end exception");
    }
}
+1

, , - -API MVC Web.

, this, , Web API global.asax IExceptionLoggers IExceptionHandler. :

  • , web.config, <customErrors mode="On"></customErrors> .
  • - Global.asax( ):

    protected void Application_Error()
    {
        if (Context.IsCustomErrorEnabled)
        {
            ShowWebErrorPage(Server.GetLastError());
        }
    }
    
    private void ShowWebErrorPage(Exception exception)
    {
        var httpException = exception as HttpException ?? new HttpException(500, "Internal Server Error", exception);
    
        Response.Clear();
        var routeData = new RouteData();
        // these depend on your Error controller logic and routing settings
        routeData.Values.Add("controller", "Error");
        routeData.Values.Add("action", "Index");
        routeData.Values.Add("statusCode", httpException.GetHttpCode());
        Server.ClearError();
    
        IController controller = new Controllers.ErrorController();
        controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));
    }
    

, - Mvc. ErrorController , .

Api , - erro html . . , :

return NotFound();

-

return Request.CreateResponse(HttpStatusCode.BadRequest, error);
0

Source: https://habr.com/ru/post/1607876/


All Articles