Asp net core return internal server error

Back in RC1, I would do this: [HttpPost] public IActionResult Post([FromBody]string something) { try{ // ... } catch(Exception e) { return new HttpStatusCodeRes...

Back in RC1, I would do this:

[HttpPost]
public IActionResult Post([FromBody]string something)
{    
    try{
        // ...
    }
    catch(Exception e)
    {
         return new HttpStatusCodeResult((int)HttpStatusCode.InternalServerError);
    }
}

In RC2, there no longer is HttpStatusCodeResult, and there is nothing I can find that lets me return a 500 type of IActionResult.

Is the approach now entirely different for what I’m asking? Do we no longer try-catch in Controller code? Do we just let the framework throw a generic 500 exception back to the API caller? For development, how can I see the exact exception stack?

John Smith's user avatar

John Smith

7,1436 gold badges48 silver badges61 bronze badges

asked Jun 13, 2016 at 15:17

Mickael Caruso's user avatar

Mickael CarusoMickael Caruso

8,43111 gold badges40 silver badges68 bronze badges

From what I can see there are helper methods inside the ControllerBase class. Just use the StatusCode method:

[HttpPost]
public IActionResult Post([FromBody] string something)
{    
    //...
    try
    {
        DoSomething();
    }
    catch(Exception e)
    {
         LogException(e);
         return StatusCode(500);
    }
}

You may also use the StatusCode(int statusCode, object value) overload which also negotiates the content.

answered Jun 13, 2016 at 15:30

Federico Dipuma's user avatar

Federico DipumaFederico Dipuma

17.4k4 gold badges42 silver badges56 bronze badges

4

You could use Microsoft.AspNetCore.Mvc.ControllerBase.StatusCode and Microsoft.AspNetCore.Http.StatusCodes to form your response, if you don’t wish to hardcode specific numbers.

return  StatusCode(StatusCodes.Status500InternalServerError);

UPDATE: Aug 2019

Perhaps not directly related to the original question but when trying to achieve the same result with Microsoft Azure Functions I found that I had to construct a new StatusCodeResult object found in the Microsoft.AspNetCore.Mvc.Core assembly. My code now looks like this;

return new StatusCodeResult(StatusCodes.Status500InternalServerError);

answered Oct 21, 2016 at 10:51

Edward Comeau's user avatar

Edward ComeauEdward Comeau

3,7642 gold badges21 silver badges22 bronze badges

4

If you need a body in your response, you can call

return StatusCode(StatusCodes.Status500InternalServerError, responseObject);

This will return a 500 with the response object…

answered Oct 4, 2018 at 6:05

David McEleney's user avatar

1

For aspnetcore-3.1, you can also use Problem() like below;

https://learn.microsoft.com/en-us/aspnet/core/web-api/handle-errors?view=aspnetcore-3.1

 [Route("/error-local-development")]
public IActionResult ErrorLocalDevelopment(
    [FromServices] IWebHostEnvironment webHostEnvironment)
{
    if (webHostEnvironment.EnvironmentName != "Development")
    {
        throw new InvalidOperationException(
            "This shouldn't be invoked in non-development environments.");
    }

    var context = HttpContext.Features.Get<IExceptionHandlerFeature>();

    return Problem(
        detail: context.Error.StackTrace,
        title: context.Error.Message);
}

answered Dec 22, 2019 at 0:44

Teoman shipahi's user avatar

Teoman shipahiTeoman shipahi

46.8k14 gold badges132 silver badges152 bronze badges

1

A better way to handle this as of now (1.1) is to do this in Startup.cs‘s Configure():

app.UseExceptionHandler("/Error");

This will execute the route for /Error. This will save you from adding try-catch blocks to every action you write.

Of course, you’ll need to add an ErrorController similar to this:

[Route("[controller]")]
public class ErrorController : Controller
{
    [Route("")]
    [AllowAnonymous]
    public IActionResult Get()
    {
        return StatusCode(StatusCodes.Status500InternalServerError);
    }
}

More information here.


In case you want to get the actual exception data, you may add this to the above Get() right before the return statement.

// Get the details of the exception that occurred
var exceptionFeature = HttpContext.Features.Get<IExceptionHandlerPathFeature>();

if (exceptionFeature != null)
{
    // Get which route the exception occurred at
    string routeWhereExceptionOccurred = exceptionFeature.Path;

    // Get the exception that occurred
    Exception exceptionThatOccurred = exceptionFeature.Error;

    // TODO: Do something with the exception
    // Log it with Serilog?
    // Send an e-mail, text, fax, or carrier pidgeon?  Maybe all of the above?
    // Whatever you do, be careful to catch any exceptions, otherwise you'll end up with a blank page and throwing a 500
}

Above snippet taken from Scott Sauber’s blog.

answered Jul 12, 2017 at 22:16

galdin's user avatar

galdingaldin

11.8k7 gold badges60 silver badges70 bronze badges

4

How about creating a custom ObjectResult class that represents an Internal Server Error like the one for OkObjectResult?
You can put a simple method in your own base class so that you can easily generate the InternalServerError and return it just like you do Ok() or BadRequest().

[Route("api/[controller]")]
[ApiController]
public class MyController : MyControllerBase
{
    [HttpGet]
    [Route("{key}")]
    public IActionResult Get(int key)
    {
        try
        {
            //do something that fails
        }
        catch (Exception e)
        {
            LogException(e);
            return InternalServerError();
        }
    }
}

public class MyControllerBase : ControllerBase
{
    public InternalServerErrorObjectResult InternalServerError()
    {
        return new InternalServerErrorObjectResult();
    }

    public InternalServerErrorObjectResult InternalServerError(object value)
    {
        return new InternalServerErrorObjectResult(value);
    }
}

public class InternalServerErrorObjectResult : ObjectResult
{
    public InternalServerErrorObjectResult(object value) : base(value)
    {
        StatusCode = StatusCodes.Status500InternalServerError;
    }

    public InternalServerErrorObjectResult() : this(null)
    {
        StatusCode = StatusCodes.Status500InternalServerError;
    }
}

answered Aug 8, 2018 at 19:35

Airn5475's user avatar

Airn5475Airn5475

2,34227 silver badges49 bronze badges

2

return StatusCode((int)HttpStatusCode.InternalServerError, e);

Should be used in non-ASP.NET contexts (see other answers for ASP.NET Core).

HttpStatusCode is an enumeration in System.Net.

answered Jul 5, 2017 at 1:50

Shimmy Weitzhandler's user avatar

When you want to return a JSON response in MVC .Net Core You can also use:

Response.StatusCode = (int)HttpStatusCode.InternalServerError;//Equals to HTTPResponse 500
return Json(new { responseText = "my error" });

This will return both JSON result and HTTPStatus. I use it for returning results to jQuery.ajax().

answered Mar 16, 2019 at 15:32

Tekin's user avatar

TekinTekin

5347 silver badges17 bronze badges

1

The built-in Problem()-method of Microsoft.AspNetCore.Mvc will return a «problem detail»-response based on RFC 7807 (in ASP.NET Core 3.0 and later). It will always return status-code 500 as long as no other status is explicitly set.

[HttpPost]
public IActionResult Post([FromBody] string value)
{
    try
    {
        // ...
    }
    catch (Exception ex)
    {
        return Problem(
            //all parameters are optional:
            //detail: "Error while processing posted data."; //an explanation, ex.Stacktrace, ...
            //instance: "/city/London"  //A reference that identifies the specific occurrence of the problem
            //title: "An error occured." //a short title, maybe ex.Message
            //statusCode: StatusCodes.Status504GatewayTimeout, //will always return code 500 if not explicitly set
            //type: "http://example.com/errors/error-123-details"  //a reference to more information
            );
    }           
}

Without setting any parameters it will return this:

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.6.1",
    "title": "An error occured while processing your request.",
    "status": 500,
    "traceId": "|fadaed95-4d06eb16160e4996."
}

More infos about «problem details» parameters:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.problemdetails?view=aspnetcore-5.0

answered Aug 23, 2021 at 12:47

volkit's user avatar

volkitvolkit

1,00314 silver badges21 bronze badges

For API Responses (using net core), I have tried this and seems that it is working fine:

var err = Content(JsonConvert.SerializeObject(response, SerializerSettings), "application/x-javascript", contentEncoding: System.Text.Encoding.UTF8);
err.StatusCode = StatusCodes.Status500InternalServerError;
return err;

You just need to create a response object first, then respond this. Doing this, we can retain the content type, encoding, and add a status code as well.

Just adding this for future reference to anybody who is stuck as well and wants a quick and easy way to do this.

answered Mar 8, 2022 at 11:28

simplecoder's user avatar

simplecodersimplecoder

2032 silver badges8 bronze badges

title author description monikerRange ms.author ms.custom ms.date uid

Handle errors in ASP.NET Core web APIs

rick-anderson

Learn about error handling with ASP.NET Core web APIs.

>= aspnetcore-3.1

riande

mvc

10/14/2022

web-api/handle-errors

Handle errors in ASP.NET Core web APIs

:::moniker range=»>= aspnetcore-7.0″

This article describes how to handle errors and customize error handling with ASP.NET Core web APIs.

Developer Exception Page

The Developer Exception Page shows detailed stack traces for server errors. It uses xref:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware to capture synchronous and asynchronous exceptions from the HTTP pipeline and to generate error responses. For example, consider the following controller action, which throws an exception:

:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_Throw»:::

When the Developer Exception Page detects an unhandled exception, it generates a default plain-text response similar to the following example:

HTTP/1.1 500 Internal Server Error
Content-Type: text/plain; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked

System.Exception: Sample exception.
   at HandleErrorsSample.Controllers.ErrorsController.Get() in ...
   at lambda_method1(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()

...

If the client requests an HTML-formatted response, the Developer Exception Page generates a response similar to the following example:

HTTP/1.1 500 Internal Server Error
Content-Type: text/html; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title>Internal Server Error</title>
        <style>
            body {
    font-family: 'Segoe UI', Tahoma, Arial, Helvetica, sans-serif;
    font-size: .813em;
    color: #222;
    background-color: #fff;
}

h1 {
    color: #44525e;
    margin: 15px 0 15px 0;
}

...

To request an HTML-formatted response, set the Accept HTTP request header to text/html.

[!WARNING]
Don’t enable the Developer Exception Page unless the app is running in the Development environment. Don’t share detailed exception information publicly when the app runs in production. For more information on configuring environments, see xref:fundamentals/environments.

Exception handler

In non-development environments, use Exception Handling Middleware to produce an error payload:

  1. In Program.cs, call xref:Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler%2A to add the Exception Handling Middleware:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Program.cs» id=»snippet_Middleware» highlight=»7″:::

  2. Configure a controller action to respond to the /error route:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_HandleError»:::

The preceding HandleError action sends an RFC 7807-compliant payload to the client.

[!WARNING]
Don’t mark the error handler action method with HTTP method attributes, such as HttpGet. Explicit verbs prevent some requests from reaching the action method.

For web APIs that use Swagger / OpenAPI, mark the error handler action with the [ApiExplorerSettings] attribute and set its xref:Microsoft.AspNetCore.Mvc.ApiExplorerSettingsAttribute.IgnoreApi%2A property to true. This attribute configuration excludes the error handler action from the app’s OpenAPI specification:

[ApiExplorerSettings(IgnoreApi = true)]

Allow anonymous access to the method if unauthenticated users should see the error.

Exception Handling Middleware can also be used in the Development environment to produce a consistent payload format across all environments:

  1. In Program.cs, register environment-specific Exception Handling Middleware instances:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConsistentEnvironments»:::

    In the preceding code, the middleware is registered with:

    • A route of /error-development in the Development environment.
    • A route of /error in non-Development environments.
  2. Add controller actions for both the Development and non-Development routes:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_ConsistentEnvironments»:::

Use exceptions to modify the response

The contents of the response can be modified from outside of the controller using a custom exception and an action filter:

  1. Create a well-known exception type named HttpResponseException:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseException.cs» id=»snippet_Class»:::

  2. Create an action filter named HttpResponseExceptionFilter:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseExceptionFilter.cs» id=»snippet_Class»:::

    The preceding filter specifies an Order of the maximum integer value minus 10. This Order allows other filters to run at the end of the pipeline.

  3. In Program.cs, add the action filter to the filters collection:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_AddHttpResponseExceptionFilter»:::

Validation failure error response

For web API controllers, MVC responds with a xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails response type when model validation fails. MVC uses the results of xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.InvalidModelStateResponseFactory to construct the error response for a validation failure. The following example replaces the default factory with an implementation that also supports formatting responses as XML, in Program.cs:

:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConfigureInvalidModelStateResponseFactory»:::

Client error response

An error result is defined as a result with an HTTP status code of 400 or higher. For web API controllers, MVC transforms an error result to produce a xref:Microsoft.AspNetCore.Mvc.ProblemDetails.

The automatic creation of a ProblemDetails for error status codes is enabled by default, but error responses can be configured in one of the following ways:

  1. Use the problem details service
  2. Implement ProblemDetailsFactory
  3. Use ApiBehaviorOptions.ClientErrorMapping

Default problem details response

The following Program.cs file was generated by the web application templates for API controllers:

:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_default»:::

Consider the following controller, which returns xref:Microsoft.AspNetCore.Http.HttpResults.BadRequest when the input is invalid:

:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Controllers/ValuesController.cs» id=»snippet_1″:::

A problem details response is generated with the previous code when any of the following conditions apply:

  • The /api/values2/divide endpoint is called with a zero denominator.
  • The /api/values2/squareroot endpoint is called with a radicand less than zero.

The default problem details response body has the following type, title, and status values:

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Bad Request",
  "status": 400,
  "traceId": "00-84c1fd4063c38d9f3900d06e56542d48-85d1d4-00"
}

Problem details service

ASP.NET Core supports creating Problem Details for HTTP APIs using the xref:Microsoft.AspNetCore.Http.IProblemDetailsService. For more information, see the Problem details service.

The following code configures the app to generate a problem details response for all HTTP client and server error responses that don’t have a body content yet:

:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_apishort» highlight=»4,8-9,13″:::

Consider the API controller from the previous section, which returns xref:Microsoft.AspNetCore.Http.HttpResults.BadRequest when the input is invalid:

:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Controllers/ValuesController.cs» id=»snippet_1″:::

A problem details response is generated with the previous code when any of the following conditions apply:

  • An invalid input is supplied.
  • The URI has no matching endpoint.
  • An unhandled exception occurs.

The automatic creation of a ProblemDetails for error status codes is disabled when the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.SuppressMapClientErrors%2A property is set to true:

:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_disable» highlight=»4-7″:::

Using the preceding code, when an API controller returns BadRequest, an HTTP 400 response status is returned with no response body. SuppressMapClientErrors prevents a ProblemDetails response from being created, even when calling WriteAsync for an API Controller endpoint. WriteAsync is explained later in this article.

The next section shows how to customize the problem details response body, using xref:Microsoft.AspNetCore.Http.ProblemDetailsOptions.CustomizeProblemDetails, to return a more helpful response. For more customization options, see Customizing problem details.

Customize problem details with CustomizeProblemDetails

The following code uses xref:Microsoft.AspNetCore.Http.ProblemDetailsOptions to set xref:Microsoft.AspNetCore.Http.ProblemDetailsOptions.CustomizeProblemDetails:

:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Program.cs» id=»snippet_api_controller» highlight=»6″:::

The updated API controller:

:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/Controllers/ValuesController.cs» id=»snippet» highlight=»9-17,27-35″:::

The following code contains the MathErrorFeature and MathErrorType, which are used with the preceding sample:

:::code language=»csharp» source=»~/../AspNetCore.Docs.Samples/fundamentals/middleware/problem-details-service/MathErrorFeature.cs» :::

A problem details response is generated with the previous code when any of the following conditions apply:

  • The /divide endpoint is called with a zero denominator.
  • The /squareroot endpoint is called with a radicand less than zero.
  • The URI has no matching endpoint.

The problem details response body contains the following when either squareroot endpoint is called with a radicand less than zero:

{
  "type": "https://en.wikipedia.org/wiki/Square_root",
  "title": "Bad Input",
  "status": 400,
  "detail": "Negative or complex numbers are not allowed."
}

View or download sample code

Implement ProblemDetailsFactory

MVC uses xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory?displayProperty=fullName to produce all instances of xref:Microsoft.AspNetCore.Mvc.ProblemDetails and xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails. This factory is used for:

  • Client error responses
  • Validation failure error responses
  • xref:Microsoft.AspNetCore.Mvc.ControllerBase.Problem%2A?displayProperty=nameWithType and xref:Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem%2A?displayProperty=nameWithType

To customize the problem details response, register a custom implementation of xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory in Program.cs:

:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ReplaceProblemDetailsFactory»:::

Use ApiBehaviorOptions.ClientErrorMapping

Use the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.ClientErrorMapping%2A property to configure the contents of the ProblemDetails response. For example, the following code in Program.cs updates the xref:Microsoft.AspNetCore.Mvc.ClientErrorData.Link%2A property for 404 responses:

:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ClientErrorMapping»:::

Additional resources

  • How to Use ModelState Validation in ASP.NET Core Web API
  • View or download sample code
  • Hellang.Middleware.ProblemDetails

:::moniker-end

:::moniker range=»= aspnetcore-6.0″

This article describes how to handle errors and customize error handling with ASP.NET Core web APIs.

Developer Exception Page

The Developer Exception Page shows detailed stack traces for server errors. It uses xref:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware to capture synchronous and asynchronous exceptions from the HTTP pipeline and to generate error responses. For example, consider the following controller action, which throws an exception:

:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_Throw»:::

When the Developer Exception Page detects an unhandled exception, it generates a default plain-text response similar to the following example:

HTTP/1.1 500 Internal Server Error
Content-Type: text/plain; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked

System.Exception: Sample exception.
   at HandleErrorsSample.Controllers.ErrorsController.Get() in ...
   at lambda_method1(Closure , Object , Object[] )
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()

...

If the client requests an HTML-formatted response, the Developer Exception Page generates a response similar to the following example:

HTTP/1.1 500 Internal Server Error
Content-Type: text/html; charset=utf-8
Server: Kestrel
Transfer-Encoding: chunked

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title>Internal Server Error</title>
        <style>
            body {
    font-family: 'Segoe UI', Tahoma, Arial, Helvetica, sans-serif;
    font-size: .813em;
    color: #222;
    background-color: #fff;
}

h1 {
    color: #44525e;
    margin: 15px 0 15px 0;
}

...

To request an HTML-formatted response, set the Accept HTTP request header to text/html.

[!WARNING]
Don’t enable the Developer Exception Page unless the app is running in the Development environment. Don’t share detailed exception information publicly when the app runs in production. For more information on configuring environments, see xref:fundamentals/environments.

Exception handler

In non-development environments, use Exception Handling Middleware to produce an error payload:

  1. In Program.cs, call xref:Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler%2A to add the Exception Handling Middleware:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Program.cs» id=»snippet_Middleware» highlight=»7″:::

  2. Configure a controller action to respond to the /error route:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_HandleError»:::

The preceding HandleError action sends an RFC 7807-compliant payload to the client.

[!WARNING]
Don’t mark the error handler action method with HTTP method attributes, such as HttpGet. Explicit verbs prevent some requests from reaching the action method.

For web APIs that use Swagger / OpenAPI, mark the error handler action with the [ApiExplorerSettings] attribute and set its xref:Microsoft.AspNetCore.Mvc.ApiExplorerSettingsAttribute.IgnoreApi%2A property to true. This attribute configuration excludes the error handler action from the app’s OpenAPI specification:

[ApiExplorerSettings(IgnoreApi = true)]

Allow anonymous access to the method if unauthenticated users should see the error.

Exception Handling Middleware can also be used in the Development environment to produce a consistent payload format across all environments:

  1. In Program.cs, register environment-specific Exception Handling Middleware instances:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConsistentEnvironments»:::

    In the preceding code, the middleware is registered with:

    • A route of /error-development in the Development environment.
    • A route of /error in non-Development environments.
  2. Add controller actions for both the Development and non-Development routes:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Controllers/ErrorsController.cs» id=»snippet_ConsistentEnvironments»:::

Use exceptions to modify the response

The contents of the response can be modified from outside of the controller using a custom exception and an action filter:

  1. Create a well-known exception type named HttpResponseException:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseException.cs» id=»snippet_Class»:::

  2. Create an action filter named HttpResponseExceptionFilter:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/HttpResponseExceptionFilter.cs» id=»snippet_Class»:::

    The preceding filter specifies an Order of the maximum integer value minus 10. This Order allows other filters to run at the end of the pipeline.

  3. In Program.cs, add the action filter to the filters collection:

    :::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_AddHttpResponseExceptionFilter»:::

Validation failure error response

For web API controllers, MVC responds with a xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails response type when model validation fails. MVC uses the results of xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.InvalidModelStateResponseFactory to construct the error response for a validation failure. The following example replaces the default factory with an implementation that also supports formatting responses as XML, in Program.cs:

:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ConfigureInvalidModelStateResponseFactory»:::

Client error response

An error result is defined as a result with an HTTP status code of 400 or higher. For web API controllers, MVC transforms an error result to produce a xref:Microsoft.AspNetCore.Mvc.ProblemDetails.

The error response can be configured in one of the following ways:

  1. Implement ProblemDetailsFactory
  2. Use ApiBehaviorOptions.ClientErrorMapping

Implement ProblemDetailsFactory

MVC uses xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory?displayProperty=fullName to produce all instances of xref:Microsoft.AspNetCore.Mvc.ProblemDetails and xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails. This factory is used for:

  • Client error responses
  • Validation failure error responses
  • xref:Microsoft.AspNetCore.Mvc.ControllerBase.Problem%2A?displayProperty=nameWithType and xref:Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem%2A?displayProperty=nameWithType

To customize the problem details response, register a custom implementation of xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory in Program.cs:

:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ReplaceProblemDetailsFactory»:::

Use ApiBehaviorOptions.ClientErrorMapping

Use the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.ClientErrorMapping%2A property to configure the contents of the ProblemDetails response. For example, the following code in Program.cs updates the xref:Microsoft.AspNetCore.Mvc.ClientErrorData.Link%2A property for 404 responses:

:::code language=»csharp» source=»handle-errors/samples/6.x/HandleErrorsSample/Snippets/Program.cs» id=»snippet_ClientErrorMapping»:::

Custom Middleware to handle exceptions

The defaults in the exception handling middleware work well for most apps. For apps that require specialized exception handling, consider customizing the exception handling middleware.

Produce a ProblemDetails payload for exceptions

ASP.NET Core doesn’t produce a standardized error payload when an unhandled exception occurs. For scenarios where it’s desirable to return a standardized ProblemDetails response to the client, the ProblemDetails middleware can be used to map exceptions and 404 responses to a ProblemDetails payload. The exception handling middleware can also be used to return a xref:Microsoft.AspNetCore.Mvc.ProblemDetails payload for unhandled exceptions.

Additional resources

  • How to Use ModelState Validation in ASP.NET Core Web API
  • View or download sample code (How to download)

:::moniker-end

:::moniker range=»< aspnetcore-6.0″

This article describes how to handle and customize error handling with ASP.NET Core web APIs.

View or download sample code (How to download)

Developer Exception Page

The Developer Exception Page is a useful tool to get detailed stack traces for server errors. It uses xref:Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware to capture synchronous and asynchronous exceptions from the HTTP pipeline and to generate error responses. To illustrate, consider the following controller action:

:::code language=»csharp» source=»handle-errors/samples/3.x/Controllers/WeatherForecastController.cs» id=»snippet_GetByCity»:::

Run the following curl command to test the preceding action:

curl -i https://localhost:5001/weatherforecast/chicago

The Developer Exception Page displays a plain-text response if the client doesn’t request HTML-formatted output. The following output appears:

HTTP/1.1 500 Internal Server Error
Transfer-Encoding: chunked
Content-Type: text/plain
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Fri, 27 Sep 2019 16:13:16 GMT

System.ArgumentException: We don't offer a weather forecast for chicago. (Parameter 'city')
   at WebApiSample.Controllers.WeatherForecastController.Get(String city) in C:working_folderaspnetAspNetCore.Docsaspnetcoreweb-apihandle-errorssamples3.xControllersWeatherForecastController.cs:line 34
   at lambda_method(Closure , Object , Object[] )
   at Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(Object target, Object[] parameters)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.SyncObjectResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Logged|12_1(ControllerActionInvoker invoker)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: */*
Host: localhost:44312
User-Agent: curl/7.55.1

To display an HTML-formatted response instead, set the Accept HTTP request header to the text/html media type. For example:

curl -i -H "Accept: text/html" https://localhost:5001/weatherforecast/chicago

Consider the following excerpt from the HTTP response:

HTTP/1.1 500 Internal Server Error
Transfer-Encoding: chunked
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/10.0
X-Powered-By: ASP.NET
Date: Fri, 27 Sep 2019 16:55:37 GMT

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title>Internal Server Error</title>
        <style>
            body {
    font-family: 'Segoe UI', Tahoma, Arial, Helvetica, sans-serif;
    font-size: .813em;
    color: #222;
    background-color: #fff;
}

The HTML-formatted response becomes useful when testing via tools like Postman. The following screen capture shows both the plain-text and the HTML-formatted responses in Postman:

:::image source=»handle-errors/_static/developer-exception-page-postman.gif» alt-text=»Test the Developer Exception Page in Postman.»:::

[!WARNING]
Enable the Developer Exception Page only when the app is running in the Development environment. Don’t share detailed exception information publicly when the app runs in production. For more information on configuring environments, see xref:fundamentals/environments.

Don’t mark the error handler action method with HTTP method attributes, such as HttpGet. Explicit verbs prevent some requests from reaching the action method. Allow anonymous access to the method if unauthenticated users should see the error.

Exception handler

In non-development environments, Exception Handling Middleware can be used to produce an error payload:

  1. In Startup.Configure, invoke xref:Microsoft.AspNetCore.Builder.ExceptionHandlerExtensions.UseExceptionHandler%2A to use the middleware:

    :::code language=»csharp» source=»handle-errors/samples/3.x/Startup.cs» id=»snippet_UseExceptionHandler» highlight=»9″:::

  2. Configure a controller action to respond to the /error route:

    :::code language=»csharp» source=»handle-errors/samples/3.x/Controllers/ErrorController.cs» id=»snippet_ErrorController»:::

The preceding Error action sends an RFC 7807-compliant payload to the client.

Exception Handling Middleware can also provide more detailed content-negotiated output in the local development environment. Use the following steps to produce a consistent payload format across development and production environments:

  1. In Startup.Configure, register environment-specific Exception Handling Middleware instances:

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseExceptionHandler("/error-local-development");
        }
        else
        {
            app.UseExceptionHandler("/error");
        }
    }

    In the preceding code, the middleware is registered with:

    • A route of /error-local-development in the Development environment.
    • A route of /error in environments that aren’t Development.
  2. Apply attribute routing to controller actions:

    :::code language=»csharp» source=»handle-errors/samples/3.x/Controllers/ErrorController.cs» id=»snippet_ErrorControllerEnvironmentSpecific»:::

    The preceding code calls ControllerBase.Problem to create a xref:Microsoft.AspNetCore.Mvc.ProblemDetails response.

Use exceptions to modify the response

The contents of the response can be modified from outside of the controller. In ASP.NET 4.x Web API, one way to do this was using the xref:System.Web.Http.HttpResponseException type. ASP.NET Core doesn’t include an equivalent type. Support for HttpResponseException can be added with the following steps:

  1. Create a well-known exception type named HttpResponseException:

    :::code language=»csharp» source=»handle-errors/samples/3.x/Exceptions/HttpResponseException.cs» id=»snippet_HttpResponseException»:::

  2. Create an action filter named HttpResponseExceptionFilter:

    :::code language=»csharp» source=»handle-errors/samples/3.x/Filters/HttpResponseExceptionFilter.cs» id=»snippet_HttpResponseExceptionFilter»:::

    The preceding filter specifies an Order of the maximum integer value minus 10. This Order allows other filters to run at the end of the pipeline.

  3. In Startup.ConfigureServices, add the action filter to the filters collection:

    :::code language=»csharp» source=»handle-errors/samples/3.x/Startup.cs» id=»snippet_AddExceptionFilter»:::

Validation failure error response

For web API controllers, MVC responds with a xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails response type when model validation fails. MVC uses the results of xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.InvalidModelStateResponseFactory to construct the error response for a validation failure. The following example uses the factory to change the default response type to xref:Microsoft.AspNetCore.Mvc.SerializableError in Startup.ConfigureServices:

:::code language=»csharp» source=»handle-errors/samples/3.x/Startup.cs» id=»snippet_DisableProblemDetailsInvalidModelStateResponseFactory» highlight=»4-13″:::

Client error response

An error result is defined as a result with an HTTP status code of 400 or higher. For web API controllers, MVC transforms an error result to a result with xref:Microsoft.AspNetCore.Mvc.ProblemDetails.

The error response can be configured in one of the following ways:

  1. Implement ProblemDetailsFactory
  2. Use ApiBehaviorOptions.ClientErrorMapping

Implement ProblemDetailsFactory

MVC uses xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory?displayProperty=fullName to produce all instances of xref:Microsoft.AspNetCore.Mvc.ProblemDetails and xref:Microsoft.AspNetCore.Mvc.ValidationProblemDetails. This factory is used for:

  • Client error responses
  • Validation failure error responses
  • xref:Microsoft.AspNetCore.Mvc.ControllerBase.Problem%2A?displayProperty=nameWithType and xref:Microsoft.AspNetCore.Mvc.ControllerBase.ValidationProblem%2A?displayProperty=nameWithType >

To customize the problem details response, register a custom implementation of xref:Microsoft.AspNetCore.Mvc.Infrastructure.ProblemDetailsFactory in Startup.ConfigureServices:

public void ConfigureServices(IServiceCollection serviceCollection)
{
    services.AddControllers();
    services.AddTransient<ProblemDetailsFactory, CustomProblemDetailsFactory>();
}

Use ApiBehaviorOptions.ClientErrorMapping

Use the xref:Microsoft.AspNetCore.Mvc.ApiBehaviorOptions.ClientErrorMapping%2A property to configure the contents of the ProblemDetails response. For example, the following code in Startup.ConfigureServices updates the type property for 404 responses:

:::code language=»csharp» source=»index/samples/3.x/Startup.cs» id=»snippet_ConfigureApiBehaviorOptions» highlight=»8-9″:::

Custom Middleware to handle exceptions

The defaults in the exception handling middleware work well for most apps. For apps that require specialized exception handling, consider customizing the exception handling middleware.

Producing a ProblemDetails payload for exceptions

ASP.NET Core doesn’t produce a standardized error payload when an unhandled exception occurs. For scenarios where it’s desirable to return a standardized ProblemDetails response to the client, the ProblemDetails middleware can be used to map exceptions and 404 responses to a ProblemDetails payload. The exception handling middleware can also be used to return a xref:Microsoft.AspNetCore.Mvc.ProblemDetails payload for unhandled exceptions.

:::moniker-end

Return HTTP Status Codes from ASPNET Core Methods 1

In this article, we will see how to return HTTP Status codes in .NET Core methods based on the HTTP Operation in API.

We shall also see the most commonly asked format like returning HTTP Status code 500 Internal server error etc.

We will cover the below aspects in today’s article,

  • Built-in HTTPS Status Code for .NET Core
  • HTTP Status Code – 200 (OK)
    • What is HTTP Status Ok or 200?
  • HTTP Status Code – 400 (Bad Request)
  • HTTP Status Code – 500 (InternalServerError )
  • Return HTTP 500 using the Status code
  • Using ProblemDetails and Best practices
  • Unhandled exception in API Pipeline?
  • Summary

Example: One may return Web API with ASP.NET Core MVC 200, 500, or 503 error codes

RESTFul services principle talks about HTTP Status code and their usage. It’s important to follow these REST HTTP Status codes appropriately when following REST specifications.

.NET Core has inbuilt support for all basic HTTP Status codes and they are easy to configure for almost all standard HTTP status codes.

RFC7231 defines the specification for this HTTP Status code in detail.

References:

  • https://tools.ietf.org/html/rfc7231#section-6.5.1

RFC7807 defines the specification for error response for HTTP error operation

References:

  • RFC7807 Problem Details HTTP error – Guidelines and Best practices

Built-in HTTPS Status Code for .NET Core

Please note that ASP.NET core provides built-in support for both RFC7231 and RFC7807, giving you direct capability on returning the standards HTTP status code plus additional details in case of error operations based on RFC specifications.

HTTP Status Code – 200 (OK)

If your controller method returns IActionResult,

What is HTTP Status Ok or 200?

  • The HTTP 200 (OK) status code indicates success.
  • This response also meant the response has the payload.
  • If no payload is desired, the server should send a 204 (NoContent) status code.

One can use the built-in type Ok() as below,

       [HttpGet]
        public IActionResult GetSynchrounous(string id)
        {
            Book book = null;
            //run method - Synchronously 
            book = _bookService.Get(id);
            return Ok(book);
        }

This built-in type does support sending additional details with its overloaded API. Please do leverage those when required.

image 11

HTTP Status Code – 400 (Bad Request)

This status code means the server cannot process the request due to malformed requests, invalid requests, etc.

One can use the built-in type BadRequest() as below,

Example:

        [HttpGet("book/{id}")]
        public IActionResult GetAccount(string id)
        {
            if (id == null)
            {
                return BadRequest();
            }
            return Ok();
        }

Below is the response for the above request (Using Chrome) will produce Status Code: 400 Bad Request,

Request URL: http://localhost:60213/api/books/book/1
Request Method: GET
Status Code: 400 Bad Request
Remote Address: [::1]:60213
Referrer Policy: no-referrer-when-downgrade

This built-in type does support sending additional details with its overloaded API.

The below response is based on RFC7807 which is a specification around how to use ProblemDetails.

Return HttpStatus code using Problem Details NET HTTP RFC 7807

Note: Controller method returning IActionResult has built-in supported Error response based on the RFC7807 Porblem details specifications.

HTTP Status Code – 500 (InternalServerError )

This status code means the server encountered an unexpected condition that prevented it from fulfilling the input request.

  • Use built-in type StatusCode()
  • Use Problem() or ProblemDetails() as per RFC7807

Return HTTP 500 using the Status code

Return HTTP 500 using the Status code below,

       
public IActionResult GetAccount1(string id)
        {
            Book book = null;
            try
            {
                //run method - Synchronously 
                book = _bookService.Get(id);

                if (book == null)
                {
                    return NotFound();
                }
                book.Price = 10;
            }
            catch (Exception ex)
            {
              return StatusCode(500, "Internal Server Error. Something went Wrong!");
            }
            return Ok(book);

Using ProblemDetails and Best practices

You can return the HTTP status code using ProblemDetails. Kindly visit the below guidelines for more details,

  • Using ProblemDetails in ASP.NET Core – Guidelines

Return HTTP 500 using ProblemDetails,

           catch (Exception ex)
            {
              return Problem("Internal Server Error.Something went Wrong!");
            }


Below is the response for the above request (Using Chrome) which produces Status Code: 500 Internal Server Error

image 12

Client-side,

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.6.1",
    "title": "An error occured while processing your request.",
    "status": 500,
    "detail": "Internal Server Error.Something went Wrong!",
    "traceId": "|5b367172-44fadfb7f6df04a9."
}

This built-in type does support sending additional details with its overloaded API.

  • StatusCode( int statusCode, object value);
  • StatusCode( int statusCode);

image 14

StatusCode can be used as an alternative for all other HTTP status codes where the built-in type is missing.

StatusCode class caN be used for all below-supported codes,

 public static class StatusCodes
    {
        public const int Status100Continue = 100;
        public const int Status412PreconditionFailed = 412;
        public const int Status413PayloadTooLarge = 413;
        public const int Status413RequestEntityTooLarge = 413;
        public const int Status414RequestUriTooLong = 414;
        public const int Status414UriTooLong = 414;
        public const int Status415UnsupportedMediaType = 415;
        public const int Status416RangeNotSatisfiable = 416;
        public const int Status416RequestedRangeNotSatisfiable = 416;
        public const int Status417ExpectationFailed = 417;
        public const int Status418ImATeapot = 418;
        public const int Status419AuthenticationTimeout = 419;
        public const int Status421MisdirectedRequest = 421;
        public const int Status422UnprocessableEntity = 422;
        public const int Status423Locked = 423;
        public const int Status424FailedDependency = 424;
        public const int Status426UpgradeRequired = 426;
        public const int Status428PreconditionRequired = 428;
        public const int Status429TooManyRequests = 429;
        public const int Status431RequestHeaderFieldsTooLarge = 431;
        public const int Status451UnavailableForLegalReasons = 451;
        public const int Status500InternalServerError = 500;
        public const int Status501NotImplemented = 501;
        public const int Status502BadGateway = 502;
        public const int Status503ServiceUnavailable = 503;
        public const int Status504GatewayTimeout = 504;
        public const int Status505HttpVersionNotsupported = 505;
        public const int Status506VariantAlsoNegotiates = 506;
        public const int Status507InsufficientStorage = 507;
        public const int Status508LoopDetected = 508;
        public const int Status411LengthRequired = 411;
        public const int Status510NotExtended = 510;
        public const int Status410Gone = 410;
        public const int Status408RequestTimeout = 408;
        public const int Status101SwitchingProtocols = 101;
        public const int Status102Processing = 102;
        public const int Status200OK = 200;
        public const int Status201Created = 201;
        public const int Status202Accepted = 202;
        public const int Status203NonAuthoritative = 203;
        public const int Status204NoContent = 204;
        public const int Status205ResetContent = 205;
        public const int Status206PartialContent = 206;
        public const int Status207MultiStatus = 207;
        public const int Status208AlreadyReported = 208;
        public const int Status226IMUsed = 226;
        public const int Status300MultipleChoices = 300;
        public const int Status301MovedPermanently = 301;
        public const int Status302Found = 302;
        public const int Status303SeeOther = 303;
        public const int Status304NotModified = 304;
        public const int Status305UseProxy = 305;
        public const int Status306SwitchProxy = 306;
        public const int Status307TemporaryRedirect = 307;
        public const int Status308PermanentRedirect = 308;
        public const int Status400BadRequest = 400;
        public const int Status401Unauthorized = 401;
        public const int Status402PaymentRequired = 402;
        public const int Status403Forbidden = 403;
        public const int Status404NotFound = 404;
        public const int Status405MethodNotAllowed = 405;
        public const int Status406NotAcceptable = 406;
        public const int Status407ProxyAuthenticationRequired = 407;
        public const int Status409Conflict = 409;
        public const int Status511NetworkAuthenticationRequired = 511;
    }

Unhandled exception in API Pipeline?

It’s recommended to use the Global exception middleware or handler approach for any unhandled exception in the API pipeline.

Users should vary on what exception should reach the consumer as a business exception Vs what can be logged in the form of technical server logging.

Kindly see below the reference article on best practices of exception handling,

  • Best Practices for Exception Handling in .NET Core
  • RFC7807 Problem Details HTTP error – Guidelines and Best practices

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!

References :

  • API Versioning Best practices in ASP.NET Core with Examples
  • Global Exception Handling in ASP.NET Core using Middleware component

Summary

It’s important to follow HTTP Status codes appropriately when following REST specifications for any communication between client and servicer. Today we learned that .NET Core has provided support for using almost all HTTP status codes allowing us to follow specifications and principles around the same based on standards RFC guidelines.


Please bookmark this page and share it with your friends. Please Subscribe to the blog to get a notification on freshly published best practices and guidelines for software design and development.


User-1158769213 posted

Hello,

I’m just starting with ASP.NET Core, and tried to deploy one today. I was faced with the above error when I tried to load it.

I started VS2017, created a new MVC Core site, and published. I didn’t change a thing, just published the site as it came out of the box.

I then copied the contents of the binReleasenetcoreapp2.2publish folder to my hosting company via FTP, and tried to load the site in a browser.

The hosting company installed Core 2.2 on the server. Do they need to do anything else? I only have control panel access (via SolidCP) to the server, not remote access, so there’s only so much I can do.

If I look in my control panel for the site, I see the following warning…

System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: System.Web.Services.Protocols.SoapException: Server was unable to process request. —> System.Runtime.InteropServices.COMException: Filename: \?D:HostingSpacestestusertest.mydomain.co.ukwwwrootweb.config 
Error: 

at Microsoft.Web.Administration.Interop.AppHostWritableAdminManager.GetAdminSection(String bstrSectionName, String bstrSectionPath) 
at Microsoft.Web.Administration.Configuration.GetSectionInternal(ConfigurationSection section, String sectionPath, String locationPath) 
at SolidCP.Providers.Web.Iis.DirectoryBrowse.DirectoryBrowseModuleService.GetDirectoryBrowseSettings(ServerManager srvman, String siteId) 
at SolidCP.Providers.Web.IIs70.FillAppVirtualDirectoryFromIISObject(ServerManager srvman, WebAppVirtualDirectory virtualDir) 
at SolidCP.Providers.Web.IIs70.GetSite(String siteId) 
at SolidCP.Providers.Web.IIs80.GetSite(String siteId) 
at SolidCP.Server.WebServer.GetSite(String siteId) 
— End of inner exception stack trace — 
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) 
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) 
at SolidCP.Providers.Web.WebServer.GetSite(String siteId) 
at SolidCP.EnterpriseServer.WebServerController.GetWebSite(Int32 siteItemId) 
at SolidCP.EnterpriseServer.esWebServers.GetWebSite(Int32 siteItemId) 
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall) 
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters) 
at SolidCP.EnterpriseServer.esWebServers.GetWebSite(Int32 siteItemId) 
at SolidCP.Portal.WebSitesEditSite.BindWebSite()

The web.config file it mentions looks like this…

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".BasicCoreSite.dll" stdoutLogEnabled="false" stdoutLogFile=".logsstdout" hostingModel="InProcess" />
    </system.webServer>
  </location>
</configuration>
<!--ProjectGuid: 2fbe438c-a8b2-4b5b-8224-eb5dfcb62107-->

I tried changing the value of stdoutLogEnabled to «true» to see if that would give me a log file, but I couldn’t see anything appear.

Anyone any idea what went wrong? The hosting company don’t know much about Core, so can’t help.

Thanks for any help you can give.

Понравилась статья? Поделить с друзьями:
  • Asp net application error
  • Asp net 1309 ошибка
  • Asp mvc error 500
  • Asmmap64 sys как исправить ошибку
  • Asmb8 ikvm java error