使用实体框架获取上一个Rest API POST的ID

时间:2019-02-13 22:52:23

标签: entity-framework rest xamarin

我需要能够访问新帖子的ID。我将使用此ID填充另一个名为LocationId的字段,如下所示:“ L” + id = LocationId(示例L22),其中22是新帖子的ID。这是我的Post请求的代码:

private async void BtnSubmit_Clicked(object sender, EventArgs e)
    {
        var imageArray = FilesHelper.ReadFully(file.GetStream());
        file.Dispose();

        var location = new Models.Location()
        {               
            LocationName = EntName.Text,
            ImageArray = imageArray,
        };
        ApiServices apiServices = new ApiServices();
        bool response = await apiServices.PostLocation(location);

        bool response2 = await apiServices.InputLocationId(id, location);
        if (!response || !response2)
        {
            await DisplayAlert("Alert", "Something wrong", "Cancel");
        }
        else
        {
            await DisplayAlert("Hi", "Your record has beed added successfully", "Alright");
        }
        await Navigation.PushAsync(new SetupPage());

这是在客户端。我在Azure SQL Server上创建了所有API(例如PostLocation和InputLocationId)。这是使用Xamarin构建的移动广告资源应用。

public async Task<bool> PostLocation(Location location)
    {
        var json = JsonConvert.SerializeObject(location);
        var httpClient = new HttpClient();
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
        var wimsApiUrl = "http://xxxxxxx.azurewebsites.net/api/Locations";
        //Get the Body of the Post
        var body = await httpClient.PostAsync(wimsApiUrl, content);
        //Convert it to a string
        var jString = await body.Content.ReadAsStringAsync();
        //Place it in a JSON Object
        JObject joResponse = JObject.Parse(jString);
        //Parse the JSON Object into an Int from a String
        var id = int.Parse(joResponse["Id"].ToString());
        //This is used in my other script to Put the LocationId of Lxx
        AddNewLocationPage.NewLocationId = id;

        return body.IsSuccessStatusCode;


    }

我的帖子位置API:

// POST: api/Locations
    [ResponseType(typeof(Location))]
    public IHttpActionResult PostLocation([FromBody] Location location)
    {
        string userId = User.Identity.GetUserId();

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        var stream = new MemoryStream(location.ImageArray);
        var guid = Guid.NewGuid().ToString();
        var file = String.Format("{0}.jpg", guid);
        var folder = "~/Content/Images";
        var fullPath = String.Format("{0}/{1}", folder, file);
        var response = FilesHelper.UploadPhoto(stream, folder, file);
        if (response)
        {
            location.ImagePath = fullPath;
        }
        var newLocation = new Location()
        {
            LocationName = location.LocationName,
            User = userId,
            ImagePath = location.ImagePath

        };
        db.Locations.Add(newLocation);
        db.SaveChanges();
        return Ok(new { newLocation.Id});
    }

然后我将获取ID并将其放入此Put请求中以创建LocationId:

public async Task<bool> InputLocationId(int id, Location location)
    {
        var json = JsonConvert.SerializeObject(location);
        var httpClient = new HttpClient();
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", Settings.AccessToken);
        var wimsApiUrl = "http://xxxxxxx.azurewebsites.net/api/Locations/InputLocationId/";
        var completeUrl = String.Format("{0}{1}", wimsApiUrl, id);
        var response = await httpClient.PutAsync(completeUrl, content);
        return response.IsSuccessStatusCode;
    }

InputLocationId API将自动创建LocationId。这是我的API:

// PUT: api/Locations/5
    [HttpPut]
    [ResponseType(typeof(void))]
    [Route("api/Locations/InputLocationId/{id}")]
    public IHttpActionResult InputLocationId(int id, [FromBody] Location location)
    {
        //string userId = User.Identity.GetUserId();

        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var result = db.Locations.FirstOrDefault(locationId => locationId.Id == id);
        var resultant = String.Format("L{0}", id);

        location.LocationName = location.LocationName;
        result.LocationId = resultant;

        db.SaveChanges();
        return Ok("The record has been updated");
    }

我只是停留在如何访问该ID上!

2 个答案:

答案 0 :(得分:0)

// get the response body
var body = await httpClient.PostAsync(wimsApiUrl, content);

// load it into a JSON object using Newtonsoft
JObject data = JObject.Parse(body);

// get the id
var id = int.Parse(data["id"]);

答案 1 :(得分:0)

需要将返回的内容从HttpResponseMessage转换为字符串。

var body = await httpClient.PostAsync(wimsApiUrl, content);
var jString = await body.Content.ReadAsStringAsync();

然后我们可以将其放入JSON对象:

JObject joResponse = JObject.Parse(jString);

现在可以将此JSON对象解析为一个Int。请注意,它需要转换为字符串。

var id = int.Parse(joResponse["Id"].ToString());