Home > OS >  StatusCodes class and HttpStatusCode enum
StatusCodes class and HttpStatusCode enum

Time:01-07

Should I use System.Net.HttpStatusCode or Microsoft.AspNetCore.Http.StatusCodes when i want to get http status code? And why there are those two similar things in .NET, when both of them seems to do the same?

Example:

public string Foo()
{
    int statusCode = StatusCodes.Status409Conflict
    // or
    int statusCode = (int)HttpStatusCode.Conflict

    return $"There is a {statusCode} here."
}

CodePudding user response:

The HttpStatusCode Enum is are inside the system.Net namespace, which means you can use it anywhere, especially when you need to read information from an API.

StatusCodes Class are inside the Microsoft.AspNetCore.Http namespace

The next one is in use, the StatusCodes class gives you the codes as an int,But in HttpStatusCode you have to cast them

Use them to position the code

CodePudding user response:

Cannot add this as a comment since I don't have the rep, but I use System.Net.HttpStatusCode in my Asp.Net Core 6 web app to check against a HttpResponse.StatusCode.

System.Net is present by default while Microsoft.AspNetCore.Http needs to be added as a dependency.

So use System.Net if you also have other services that depend on it (ex: IPEndPoint). No need to install a separate package.

You can find more info here

TLDR: This is all due to Asp.Net Core's messy ecosystem

  • Related