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

Raz*_*mil 2 c# push-notification asp.net-web-api

我希望以下 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;
}
Run Code Online (Sandbox Code Playgroud)

Nko*_*osi 6

让动作的结果是一个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
}
Run Code Online (Sandbox Code Playgroud)

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

{
  "error": {
    "code": 400,
    "message": "installation id is null or empty"
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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;

    //...
}

//...
Run Code Online (Sandbox Code Playgroud)