gpt4 book ai didi

c# - 如何在 Web API Post 方法中返回自定义消息

转载 作者:行者123 更新时间:2023-12-02 14:55:11 29 4
gpt4 key购买 nike

我希望以下 Post 方法通过将失败值分配给“result”变量来返回失败,但我不确定如何实现。理想情况下,它会说安装 ID 无效,但不确定我是否可以这样做:

[Authorize]
[HttpPost, Route("sendForDevelopment")]
public async Task<NotificationOutcome> Post([FromBody]string message, string installationId)
{

string hubName = "myHubName";
string hubNameDefaultShared = "myHubNameDefaultShared";

NotificationHubClient hub = NotificationHubClient
.CreateClientFromConnectionString(hubNameDefaultShared, hubName, enableTestSend: true);

var templateParams = new Dictionary<string, string>
{
["messageParam"] = message
};

NotificationOutcome result = null;

if (string.IsNullOrWhiteSpace(installationId))
{
// output a installation id is null or empty message or assign failure to the result variable
}
else
{
result = await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}").ConfigureAwait(false);
}

return result;
}

最佳答案

将操作的结果作为 IHttpActionResult 派生对象。

当请求无效时,您可以更灵活地返回什么

例如

[Authorize]
[HttpPost, Route("sendForDevelopment")]
public async Task<IHttpActionResult> Post([FromBody]string message, string installationId) {

if (string.IsNullOrWhiteSpace(installationId)) {
var model = new {
error = new {
code = 400,
message = "installation id is null or empty"
}
}
return Content(HttpStatusCode.Badrequest, model); //400 Bad Request with error message
}

string hubName = "myHubName";
string hubNameDefaultShared = "myHubNameDefaultShared";

var hub = NotificationHubClient
.CreateClientFromConnectionString(hubNameDefaultShared, hubName, enableTestSend: true);

var templateParams = new Dictionary<string, string>
{
["messageParam"] = message
};

NotificationOutcome result = await hub.SendTemplateNotificationAsync(templateParams, "$InstallationId:{" + installationId + "}").ConfigureAwait(false);
return Ok(result); //200 OK with model result
}

对于错误的请求,响应正文看起来像这样

{
"error": {
"code": 400,
"message": "installation id is null or empty"
}
}

在客户端,您检查响应的状态代码并进行相应处理。

var response = await client.PostAsync(url, content);
if(response.IsSuccessStatusCode)
var result = await response.Content.ReadAsAsync<NotificationOutcomeResult>();

//...
else {
//...check why request failed.
var model = await response.Content.ReadAsAsync<ErrorResponse>();

var message = model.error.message;

//...
}

//...

关于c# - 如何在 Web API Post 方法中返回自定义消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53309884/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com