简体   繁体   中英

How to Add Uri to the Created(Status Code 201) of a Post Request

i just started learning asp.net core api and i'm trying to make a post request from Postman. I want to return a status code of 201 upon post and return the Uri of the newly posted data as the location. Below is my controller code

    [HttpPost]
    public ActionResult CreateMake([FromBody]MakeResource makeresource)
    {
        if (!ModelState.IsValid) {
            return BadRequest(ModelState) ;
        }
       var makes = mapper.Map<MakeResource, Make>(makeresource);
        _makes.AddMake(makes);
        makeresource.Id = makes.Id;

        return Created(new Uri(Request.Path, UriKind.Relative), makeresource);
    }

I get an error

System.UriFormatException: 'Invalid URI: The format of the URI could not be determined.'

and I guess it has to do with the Uri(Request.Path). In Asp.net web api, I would implement it as return Created(new Uri(Request.Uri + "/" + makes.Id), makeresource); and the action type would be IHttpActionResult instead of ActionResult as shown in my controller but it doesn't work that way in asp.net core. Any assistance on how to solve this issue would be needed. Thanks.

I just want to put this here, incase anybody needs it in the future. I got the answer i used from What is the ASP.NET Core MVC equivalent to Request.RequestURI?

I solved my issue by replacing (Request.Path, UriKind.Relative) with as (Request.GetEncodedUrl()+ "/" + makes.Id) seen below:

return Created(new Uri(Request.GetEncodedUrl()+ "/" + makes.Id), makeresource);

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