我有一个带有 2 种方法的 ODataController:
[EnableQuery]
public SingleResult<item> Getitem([FromODataUri] System.Guid key)
{
return SingleResult.Create(db.items.Where(item=> item.guid == key));
}
public async Task<IHttpActionResult> Postitem([FromODataUri] System.Guid key, [FromBody] double itemId)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
//Find the correct account
item i = await db.items.FirstAsync(item=> item.guid == key);
if (i == null)
{
return NotFound();
}
//Update the account field we are using for id
i.itemId = itemId;
//Save the changes
try
{
await db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!itemExists(key))
{
return NotFound();
}
else
{
throw;
}
}
return Updated(i);
}
private bool itemExists(System.Guid key)
{
return db.items.Count(e => e.guid == key) > 0;
}
使用标准的 WebApiConfig:
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
config.EnableCors();
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<item>("items");
config.Routes.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
我可以在 url 栏中输入 mydomain.com/odata/items(guid'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX') 并将数据库对象获取为 json 就好了。
但是当我尝试以下客户端代码时:
var itemGuid = "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX";
var itemId = "55555";
using (WebClient wc = new WebClient())
{
wc.UseDefaultCredentials = true;
var domain = "mydomain.com";
var url = domain + "/odata/items(guid'" + itemGuid + "')";
var data = new NameValueCollection();
data["itemId"] = itemId;
byte[] temp = wc.UploadValues(url, "POST", data);
context.Response.Write(Encoding.UTF8.GetString(temp));
}
我得到远程服务器返回错误:(404)未找到。
我知道这可能是一个简单的错误,但已经搞砸了太久,而且我是 asp.net 的新手。