How can I transfer the status code from my C# class to my TypeScript client application in ASP.NET Core?

One of my challenges involves working with the ProjectDecommissionRequestController controller and a TypeScript client app. The TypeScript client app is designed to print specific strings based on status codes, such as displaying a generic error message for a 500 status code.

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);

In the controller, there is a call to another class that performs a 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 am looking to adjust the status code for this exception to something other than 500 in order to provide a more specific error message.

Any suggestions or assistance would be greatly appreciated. Thank you!

Answer №1

To easily handle status codes, you can utilize the StatusCode method:

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

Additonally, there are convenient shortcut methods available for frequently used status codes such as: BadRequest NotFound and more.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Hiding a navigation bar in Xamarin.Forms

I am a beginner in Xamarin.Forms and C#, and I have a question about how to display a stack of Pages within a NavigationPage without showing the navigation bar. Here is the code snippet from my App.cs file: using Xamarin.Forms; namespace Test ...

What is the correct method to have a React component update its rendering every minute?

In my React-Native project with TypeScript, I'm encountering an issue where I need a component to rerender every minute, even if the state derived from a selector remains unchanged. The output of the selector is influenced by a function called datePro ...

Implement pagination in ASP.NET MVC views efficiently without redundantly executing SQL queries

Currently, I am dealing with a situation where I have a substantial dataset retrieved from a stored procedure that needs to be displayed in pages on an ASP.NET webpage. Unfortunately, I am unable to request support for pagination from the DBAs, so I have t ...

How can I fetch a file using a JavaScript function in Pug/Angular?

Within the Angular7/Pug application, there was previously a file download link implemented in table.component.pug like this: div p File to download: a([href]="downloadLink", download="table.xlsx") some-icon span some-text Now, I a ...

The Ajax UpdatePanel embedded within the repeater seems to be lacking the necessary post back

I am facing an issue with postback of the UpdatePanel inside the repeater. <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <asp:Repeater ID="Posts" runat="server" OnItemCreated="Posts_OnItemCreated"> <I ...

Angular 2 Component attribute masking

In my Angular 2 component called Foobar, I have defined a property named foobar: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-foobar', templateUrl: './foobar.component ...

Decrease the construction duration within a sprawling Angular 8 project

It takes nearly 10-15 minutes to compile the project in production mode, resulting in a dist folder size of 32MB Here are the production options I am currently using:- "production": { "optimization": true, "outputHashing": "all", ...

The Karma testing feature in Angular Quickstart encounters issues right from the start

When attempting to run karma tests after a clean install of the official Angular quickstart on Windows 10, I encountered an issue. Following a series of four commands, here is what happened: C:\projects\temp>git clone https://github.com/angul ...

Passing an integer value from AJAX to a View in ASP.NET Core

For ASP.NET Core, my goal is to transfer a value from ajax to view. I have an action that sends an int value to an ajax call. The ajax then instructs the view to either blink or not. Below is the code snippet for the controller: public ActionResult GetCo ...

Exploring the concept of inheritance within ASP.Net Pages

As a newcomer to programming, I am currently diving into OOPs concepts and recently came across the idea of "inheritance" (the process of creating a new class based on an existing one). While exploring a new project in asp.net, I stumbled upon the followi ...

Creating a Webgrid in MVC and integrating it with a custom class in AngularJS

Hey there, I'm a beginner when it comes to AngularJS and I'm looking to bind the webgrid within the method of AngularJS. $scope.SaveDetails = function () { debugger; var UserID = '@Session["ID"]'; ...

Does NodeJS have a counterpart to C#'s GetAwaiter function?

Here is the code I am working with: async function testingFunction() { var mongo = await MongoClient.connect(connectionString); var db = await mongo.db(databaseName); var auditCollection = db.collection(collectionName); var result = await ...

Dynamic Input Rows in ASP.NET are a versatile feature that allows users to

My ASP.NET web application form requires users to input various details, including: Subject Code Subject Name Subject Details ....etc I want to make it easy for users by allowing them to click on a plus (+) or add button that will create ...

Unveiling the Mystery of Angular: Why are constructor parameters without access specifiers hidden from view outside the

When I explicitly set an access specifier for a constructor parameter, it becomes visible outside the constructor. For example: constructor(private employeResourceService:EmployeeResourceService ){ //code} ngOnInit(){ this.employeResourceService=unde ...

Tips for integrating Material-Ui Autocomplete with Formik's Field component to create Multi-Select check boxes

Trying to integrate Formik's Field component with Material-Ui Autocomplete for multiple values that include checkboxes has been challenging. Whenever a value is selected from the dropdown list, the popup closes and needs to be reopened for the next se ...

AutoComplete TextBox does not automatically fill in additional fields

I am experiencing difficulty in getting a TextBox with AutoCompleteExtender to update other fields once a selection is made. Interestingly, when I attempt the same process with a DropDownList (making necessary control name changes) it works flawlessly. Ca ...

The positioning of CSS arrows using the "top" attribute is not relative to the top of the page when using absolute values

I am currently working on positioning the arrow in the screenshot using TypeScript calculations. However, I am facing an issue where the position is being determined based on the top of the black popup instead of the top of the screen. From the top of the ...

Adding CSS styles to an HTML generic control such as <UL> and <LI> in an ASP.NET application

I am struggling to apply CSS to an HTML generic control like <UL> and <LI> with the attribute runat="server" in ASP.NET. Specifically, I need to target the <li> element located within a master page from a content page. Once I locate thi ...

Is it possible for a malicious party to modify the src attribute within an iframe?

My website incorporates IFrame on a page, loading different pages based on server-side logic. As such, the source code appears like this when viewed: <iframe src="DeterminedOnServerSide.aspx" id="myFrame"> </iframe> I am curious if there is a ...

Is it possible to customize a row with checkboxes in ng2-smart-table when creating a new row?

When adding a new row, I would like a checkbox in the Status column and an input text field in the Image column. You can see an example image here. ...