.NET MVC 4 WebAPI POST不起作用 [英] .NET MVC 4 WebAPI POST not working
问题描述
核心问题:GET有效,POST不起作用.我是WebAPI的新手,所以我可能在做一些愚蠢的事情,但是我在网上搜寻了很多,试图弄清为什么它不起作用.
Core problem: GET works, POST doesn't. I'm new to WebAPI so I'm probably doing something stupid, but I've poked around quite a bit on the 'net trying to figure out why this isn't working.
相当简单的WebAPI C#应用程序.我试图将其归结为非常简单的路线:
Fairly simple WebAPI C# app. I've tried to get this down to very simple routes:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// Add a route where action is supplied, i.e. api/csv/LoadToSQL
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}"
);
控制器类:
public class CsvController : ApiController
{
// GET api/csv
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/csv/name
public string Get(string csvName)
{
return "value";
}
// POST - api/csv/LoadToSQL
// Load a CSV to SQL
[HttpPost]
[ActionName("LoadToSQL")]
public HttpResponseMessage LoadToSQL(
string storageAccount,
string accessKey,
string containerName,
string csvFileName,
string connectionString,
string targetDatabaseName,
string targetTableName)
{
try
{
// Retrieve storage account from connection string.
CloudStorageAccount blobStorage = CloudStorageAccount.Parse(storageAccount);
在本地启动并连接Fiddler.尝试GET;作品:
Start it up locally and connect Fiddler. Try a GET; works:
尝试POST-失败:
我最初的实现只有
// POST - api/csv
// Load a CSV to SQL
public HttpResponseMessage Post(
但是没有用,所以我开始尝试添加特定的路线和动词修饰.
but that didn't work so I started trying to add specific routes and verb decorations.
无论我做什么,似乎都没有看到针对此控制器的POST动作.
It just doesn't seem to see the POST action against this controller no matter what I do.
有什么想法吗?
更新-以下每个答案的正确答案是:
UPDATE - per answer below, the correct route to make this work is:
// Add a route where action is supplied, i.e. api/csv/LoadToSQL
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{storageAccount}/{accessKey}/{containerName}/{csvFileName}/{connectionString}/{targetDatabaseName}/{targetTableName}"
);
这显示了POST请求的所有参数.
This shows all the parameters to the POST request.
推荐答案
如果愿意,您可以替换您的方法以使其更清晰,更干净
You can replace your method to be more clear and clean if you like so
1-使用您的选项声明一个类
1- declare a class with your options
public class LoadToSqlData
{
public string storageAccount {get; set;}
public string accessKey {get; set;}
public string containerName {get; set;}
public string csvFileName {get; set;}
public string connectionString {get; set;}
public string targetDatabaseName {get; set;}
public string targetTableName {get; set;}
}
2-声明您的方法是:
2- Declare your method to be :
[HttpPost]
[ActionName("ActionApi")]
[Route("api/Csv/LoadToSQL")]
public HttpResponseMessage LoadToSQL([FromBody]LoadToSqlData data)
注意[Route],[ActionName]
和[FromBody]
属性的用法.
希望有帮助.
这篇关于.NET MVC 4 WebAPI POST不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!