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

    评论

报告相同问题?