如何在C#中使用自定义消息显示状态代码? [英] How to show the status code with custom message in c#?
问题描述
在MVC5中,我使用下面的代码返回带有自定义消息的状态代码.它在我的输出中显示提供的消息.
In MVC5, I have used the below code to return the status code with a custom message. It shows the provided message in my output.
return new HttpStatusCodeResult(403, "Not allowed");
在.net核心框架中,以上方法不适用,因此我尝试了以下方法,但找不到如何传递自定义消息.
In .net core framework, above method is not applicable, so I tried the below method but I didn't find how to pass the custom message.
StatusCode(403)
它将默认消息显示为禁止"
It shows the default message as "Forbidden"
如何在StatusCode中提供自定义消息?还有其他方法可用吗?
How can I provide the custom message in StatusCode? Are any other methods available?
推荐答案
我发现ContentResult
给出了最简单和可用的结果:
I found ContentResult
to give the most simple and usable results:
private static ActionResult Result(HttpStatusCode statusCode, string reason) => new ContentResult
{
StatusCode = (int)statusCode,
Content = $"Status Code: {(int)statusCode}; {statusCode}; {reason}",
ContentType = "text/plain",
};
只需返回该调用即可使用它:
Use it by simply returning that call:
return Result(HttpStatusCode.Unauthorized, "Invalid token");
这将导致文本为Status Code: 401; Unauthorized; Invalid token
的401.
This will result in a 401 with the text Status Code: 401; Unauthorized; Invalid token
.
这篇关于如何在C#中使用自定义消息显示状态代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!