简体   繁体   中英

MVC and fail AJAX call

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 (ie 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM