简体   繁体   中英

ASP.NET Core - How do I get my status code from my C# class to my TypeScript Client App?

I have this controller called ProjectDecommissionRequestController.

And I have this TypeScript client app which basically prints a certain string according to the status code (for eg gives a generic error in case of status code 500).

const response = await fetch(`api/projectdecommissionrequest`, {
    body: JSON.stringify(postBody),
    headers: new Headers({
        "Accept": "application/json",
        "Authorization": `Bearer ${token}`,
        "Content-Type": "application/json",
    }),
    method: "POST",
});
console.log(response.status);

My controller calls another class which performs this check and throws an error -

 if (!repoUrlFormatMatch.Success)            
                throw new FormatException($"The repositoryUri '{repositoryUri}' did not conform to the expected format for an Azure Devops Git repository.");

I want to set the status code for this exception to be something other than 500 so that I can write a more specific error.

Any help will be appreciated. Thank you!

You can use StatusCode method:

        public ActionResult MyMethodWithStatusCode(int code)
        {
            return StatusCode(code);
        }

There are also shortcut methods for commonly used codes: BadRequest NotFound etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM