简体   繁体   English

ASP.NET 核心 - 如何从我的 C# class 到我的 Z558B5744CF685F39D34EZ906B 客户端应用程序中获取我的状态代码?

[英]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.我有这个名为 ProjectDecommissionRequestController 的 controller。

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).我有这个 TypeScript 客户端应用程序,它基本上根据状态代码打印某个字符串(例如,在状态代码 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 -我的 controller 调用另一个 class 执行此检查并引发错误 -

 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.我想将此异常的状态代码设置为 500 以外的值,以便我可以编写更具体的错误。

Any help will be appreciated.任何帮助将不胜感激。 Thank you!谢谢!

You can use StatusCode method:您可以使用StatusCode方法:

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

There are also shortcut methods for commonly used codes: BadRequest NotFound etc.常用代码也有快捷方式: BadRequest NotFound等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在控制台应用程序中重用来自我的 ASP.NET Core MVC 应用程序的代码:如何进行数据库连接 - Reusing code from my ASP.NET Core MVC app in console app : how to do database connection 如何制作一个 ASP.NET C# 电子邮件应用程序供用户从我的网站发送反馈? - How do I make an ASP.NET C# email app for user's to send feedback from my website? C#ASP.NET MVC:如何让浏览器从我的响应中自动下载pdf? - C# ASP.NET MVC: How do I get the browser to automatically download a pdf from my response? 为什么我不能在我的代码asp.net c#中使用app_code中的代码文件 - why I can't use code files from app_code in my code asp.net c# 如何使用asp.net将值从C#发送到javascript - How do I send my values from c# to javascript with asp.net ASP.NET C#如何在代码中包含模型? - ASP.NET C# How can I include my models in my code? 如何在C#中的ASP.NET应用程序中调用Web方法? - How can I call my webmethod in my ASP.NET app in c#? 如何从我的ASP.NET Core MVC应用程序中的类库记录NLog调用? - How to log NLog calls from a class library in my ASP.NET Core MVC app? 我如何告诉 MVC 中间件我的 class 是 ASP.NET Core 中的一个 Controller? - How do I tell the MVC middleware that my class is a Controller in ASP.NET Core? 如何向我的 MVC asp.net Core 应用程序添加排序功能? - How do I add a sorting feature to my MVC asp.net Core app?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM