【发布时间】:2012-10-09 00:19:24
【问题描述】:
我在 Windows 应用商店应用程序中运行了以下代码,应该调用我的 WebApis 之一:
using (var client = new HttpClient())
{
var parms = new Dictionary<string, string>
{
{"vinNumber", vinNumber},
{"pictureType", pictureType},
{"blobUri", blobUri}
};
HttpResponseMessage response;
using (HttpContent content = new FormUrlEncodedContent(parms))
{
const string url = "http://URL/api/vinbloburis";
response = await client.PostAsync(url, content);
}
return response.StatusCode.ToString();
}
WebApi 代码如下所示:
[HttpPost]
public HttpResponseMessage Post(string vinNumber, string pictureType, string blobUri)
{
var vinEntity = new VinEntity
{
PartitionKey = vinNumber,
RowKey = pictureType,
BlobUri = blobUri
};
_vinRepository.InsertOrUpdate(vinEntity);
return new HttpResponseMessage { Content = new StringContent("Success"), StatusCode = HttpStatusCode.OK };
}
使用 Fiddler,我观察到以下情况......这是请求的样子:
POST http://URL/api/vinbloburis HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Host: URL
Content-Length: 113
Expect: 100-continue
vinNumber=vinNumber&pictureType=top&blobUri=https%3A%2F%2Fmystorage.blob.core.windows.net%2Fimages%2Fimage.png
但响应是一个错误,信息很少/没有:
{"Message":"An error has occurred."}
我什至在本地尝试使用附加到 WebApis 的调试器,但我的 Post 方法从未捕获。
有人看到我在这里错过的东西吗?我觉得我正在看它,但没有看到它。我应该补充一点,我可以在通过查询字符串传递参数时调用 HttpGet 方法。现在问题只出在这个 HttpPost 上。
谢谢!
更新:基于来自人们的一些优秀的 cmets,我正在添加更多细节。
我为 WebApis 配置了默认路由 ...
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
因此,我认为 /URL/api/vinbloburis 应该可以工作。此外,如上所述,我目前正在使用 HttpGet。以下是 Windows 应用商店应用程序调用 HttpGet WebApi 的工作原理......
using (var client = new HttpClient())
{
using (var response = await client.GetAsync(uri))
{
if (response.IsSuccessStatusCode)
{
var sasUrl = await response.Content.ReadAsStringAsync();
sasUrl = sasUrl.Trim('"');
return sasUrl;
}
}
}
... 它正在调用以下 WebApi ...
[HttpGet]
public HttpResponseMessage Get(string blobName)
{
const string containerName = "images";
const string containerPolicyName = "policyname";
_helper.SetContainerPolicy(containerName, containerPolicyName);
string sas = _helper.GenerateSharedAccessSignature(blobName, containerName, containerPolicyName);
return new HttpResponseMessage
{
Content = new StringContent(sas),
StatusCode = HttpStatusCode.OK
};
}
希望其他信息对您有所帮助!
【问题讨论】:
-
只是为了确认 - 您是否更改了您正在调用的方法的名称?目前您的代码示例的方法名称为 POST 但您的 HTTP 请求正在尝试调用 vinbloburis ?这会导致您看到的错误。
-
如果你从提琴手做 POST,它有效吗?
-
您尝试过使用 PostJsonAsync 吗?你能分享你的路由配置吗?
-
这些都是很好的问题,伙计们! @LewisBenge,我认为这不是问题 - 我已经分享了 WebApis 的注册方式以及与 HttpGet 相关的一些附加信息。
标签: c# asp.net-web-api windows-store-apps