简体   繁体   中英

WebAPI C# HttpPost variable is empty

I have a webapi method defined like the following in a controller:

[Authorize]
[HttpPost]
[Route("api/Resources/{resourceID:int}/VerifyUrl")] //Custom Routing 
public object VerifyResourceURL([FromBody]string url, int resourceID)

When I call it with jquery ajax the variable url is always null, why?

(resourceID has the correct value)

$.ajax({
    url: '/api/resources/15/VerifyUrl',
    type: "POST",
    async: true,
    dataType: "json",
    data: { url: 'some-url-to-verify' }, 
    success: function (data) {
        if (data.Exist === false) {
            urlIsValid = true;
        }
        else {
            alert('URL already exist');
            urlIsValid = false;
        }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        console.log("Status: " + textStatus, "Error: " + errorThrown);
    }
});

You're sending an object with a url property, but expecting the body to be a string.

Try changing datatype and data as such:

dataType: "text",
data: 'some-url-to-verify', 

I have sample code and you can try something like this

//JavaScript
     var command = {
                    url: $("#txtOrigin").val()               
                };



        $.ajax({
            type: "POST",
            url: "/api/booking",
            contentType: "application/json",
            data: JSON.stringify(command),
            dataType: "text",
            success: Created,
            error: Failed
        });

//C# MVC Controller
public async Task<IActionResult> Create([FromBody] CreateBookingCommand command)
{

}

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