带有Windows 8商店应用程序的Web API

时间:2013-09-25 12:46:28

标签: c# asp.net-web-api winrt-xaml

我正在尝试访问web api Post方法,使用Windows 8商店应用程序将记录插入表中。

我的Web API Post方法如下所示:

public HttpResponseMessage Post([FromBody]DeviceLog deviceLog)
{
try
 {
 if (ModelState.IsValid)
                {
                    var sqlCon = new SqlConnection(@"Data Source=local;Initial Catalog=mydatabase;User ID=sa;Password=sa");
                    const string query = "INSERT INTO [IECMSDBV2].[dbo].[DeviceLog] ([LogDate],[LogFrom],[OperatingSystem],[OSVersion],[MachineID],[ModelName],[FriendlyName],[IPAddress],[Country])VALUES(@LogDate,@LogFrom,@OperatingSystem,@OSVersion,@MachineID,@ModelName,@FriendlyName,@IPAddress,@Country)";
                    var sqlcmd = new SqlCommand(query, sqlCon);

                    if (sqlCon.State == ConnectionState.Closed)
                    {
                        sqlCon.Open();
                    }

                    sqlcmd.Parameters.Add(new SqlParameter("@LogDate", SqlDbType.DateTime));
                    sqlcmd.Parameters["@LogDate"].Value = DateTime.Now;

                    sqlcmd.Parameters.Add(new SqlParameter("@LogFrom", SqlDbType.NVarChar));
                    sqlcmd.Parameters["@LogFrom"].Value = deviceLog.LogFrom;

                    sqlcmd.Parameters.Add(new SqlParameter("@OperatingSystem", SqlDbType.NVarChar));
                    sqlcmd.Parameters["@OperatingSystem"].Value = deviceLog.OperatingSystem;

                    sqlcmd.Parameters.Add(new SqlParameter("@OSVersion", SqlDbType.NVarChar));
                    sqlcmd.Parameters["@OSVersion"].Value = deviceLog.OperatingSystemVersion;

                    sqlcmd.Parameters.Add(new SqlParameter("@MachineID", SqlDbType.NVarChar));
                    sqlcmd.Parameters["@MachineID"].Value = deviceLog.MachineId;

                    sqlcmd.Parameters.Add(new SqlParameter("@ModelName", SqlDbType.NVarChar));
                    sqlcmd.Parameters["@ModelName"].Value = deviceLog.ModelName;

                    sqlcmd.Parameters.Add(new SqlParameter("@IPAddress", SqlDbType.NVarChar));
                    sqlcmd.Parameters["@IPAddress"].Value = deviceLog.IpAddress;

                    sqlcmd.Parameters.Add(new SqlParameter("@Country", SqlDbType.NVarChar));
                    sqlcmd.Parameters["@Country"].Value = deviceLog.Country;

                    sqlcmd.ExecuteNonQuery();

                    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, deviceLog);
                    //response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = 29292 }));
                    return response;
                }
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
            catch (Exception)
            {
                 return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);

            }
        }
在Windows 8商店应用程序上的

我写了以下代码:

 private async Task<bool> UploadData(DeviceLog deviceLog)
        {
            bool returnvalue = true;

            httpClient = new HttpClient();
            httpClient.BaseAddress = new Uri("http://localhost:54230/");
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.MaxResponseContentBufferSize = 266000;
            try
            {
                using (var memStream = new MemoryStream())
                {
                    var data = new DataContractJsonSerializer(typeof (DeviceLog));
                    data.WriteObject(memStream, deviceLog);
                    memStream.Position = 0;
                    var contentToPost = new StreamContent(memStream);
                    contentToPost.Headers.ContentType =
                        new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                    var resp =
                        await httpClient.PostAsync(new Uri("http://localhost:54230/api/DeviceLog"), contentToPost);

                    resp.EnsureSuccessStatusCode();
                }
            }
            catch (Exception ex)
            {
                returnvalue = false;
                _general.WriteError(ex);
            }

           return returnvalue;
        }

当我执行此操作时,我收到以下错误:

{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Pragma: no-cache
  X-SourceFiles: =?UTF-8?B?RTpcQ29kZVxMaXZlIFByb2plY3RzXElFQ01TVjJcSUVDTVNWMi5XZWJBUElcYXBpXERldmljZUxvZw==?=
  Cache-Control: no-cache
  Date: Wed, 25 Sep 2013 12:38:32 GMT
  Server: Microsoft-IIS/8.0
  X-AspNet-Version: 4.0.30319
  X-Powered-By: ASP.NET
  Content-Length: 1460
  Content-Type: application/json; charset=utf-8
  Expires: -1
}}
    Content: {System.Net.Http.StreamContent}
    Headers: {Pragma: no-cache
X-SourceFiles: =?UTF-8?B?RTpcQ29kZVxMaXZlIFByb2plY3RzXElFQ01TVjJcSUVDTVNWMi5XZWJBUElcYXBpXERldmljZUxvZw==?=
Cache-Control: no-cache
Date: Wed, 25 Sep 2013 12:38:32 GMT
Server: Microsoft-IIS/8.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
}
    IsSuccessStatusCode: false
    ReasonPhrase: "Internal Server Error"
    RequestMessage: {Method: POST, RequestUri: 'http://localhost:54230/api/DeviceLog', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
  Accept: application/json
  Content-Type: application/json
  Content-Length: 312
}}
    StatusCode: InternalServerError
    Version: {1.1}

记录也没有上传到数据库中。 请指导我。

感谢阅读

干杯

六必居

0 个答案:

没有答案