weixin_33708432 2018-08-01 14:32 采纳率: 0%
浏览 21

MVC和AJAX调用失败

I have a controller method:

    public async Task SaveRouting(string points, int tripId, decimal totalMileage)
    {
        if (Request.IsAjaxRequest())
        {
            //....
            await _serviceTrip.UpdateTotalMileageAsync(tripId, totalMileage);
        }
        else
            throw new Exception("Only ajax calls are allowed");
    }

so, as we can see, this method returns Task, so nothing to client. But if something wrong (i.e. totalMileage is less or equal 0) I want to return 422 status code and dictionary with invalid data, like: { "totalMileage" : "Total mileage should be greater than 0" }

How to do it? I try to do it:

            if (totalMileage <= 0)
            {
                Response.StatusCode = 422; // 422 Unprocessable Entity Explained
            }

but how to describe an error?

  • 写回答

1条回答 默认 最新

  • weixin_33728708 2018-08-01 16:53
    关注

    If you want to describe the error after setting Response.StatusCode, then you have to write into the body of the http response by calling Response.Body.Write(byte[],int, int). Therefore, you can convert your response message to a byte array using the following method:

    public byte[] ConvertStringToArray(string s)
    {
        return new UTF8Encoding().GetBytes(s);
    }
    

    And then use it like this:

    byte[] bytes = ConvertStringToArray("Total mileage should be greater than 0");
    Response.StatusCode = 422;
    Response.Body.Write(bytes,0,bytes.Length);
    

    But you can further simplify this using extension methods on ControllerBase

    评论

报告相同问题?

悬赏问题

  • ¥15 onlyoffice编辑完后立即下载,下载的不是最新编辑的文档
  • ¥15 求caverdock使用教程
  • ¥15 Coze智能助手搭建过程中的问题请教
  • ¥15 12864只亮屏 不显示汉字
  • ¥20 三极管1000倍放大电路
  • ¥15 vscode报错如何解决
  • ¥15 前端vue CryptoJS Aes CBC加密后端java解密
  • ¥15 python随机森林对两个excel表格读取,shap报错
  • ¥15 基于STM32心率血氧监测(OLED显示)相关代码运行成功后烧录成功OLED显示屏不显示的原因是什么
  • ¥100 X轴为分离变量(因子变量),如何控制X轴每个分类变量的长度。