有人可以帮忙吗?我有这个控制器:
public class CbpOutcomeController : ApiController
{
// POST /api/CbpOutcome/1/
public HttpResponseMessage PostCreateCbpOutcome(CbpOutcome co)
{
... snip ...
return resp_msg;
}
}
Run Code Online (Sandbox Code Playgroud)
这条路线:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"HubProfilePostRoute", // Route name
"hub/{controller}/{action}", // URL with parameters
new { controller = "Home", action = "Index" } // Parameter defaults
);
routes.MapHttpRoute(
name: "ProfileByRegionApi",
routeTemplate: "api/{controller}/Region/{region_name}"
);
routes.MapHttpRoute(
name: "ProfileByGlobalPriorityApi",
routeTemplate: "api/{controller}/GlobalPriority/{priority_name}"
);
routes.MapHttpRoute(
name: "ApiRoute",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional …Run Code Online (Sandbox Code Playgroud) 我有一个Web API项目作为我的解决方案的一部分(也包含一个MVC4项目),在Api项目中我试图将一个表单发布到Values控制器Post方法(从Api项目中的视图).
使用Html.BeginForm()或Html.BeginForm("Post", "Values")发布,/Values/Post但我需要它去/api/Values/Post
知道我需要将哪些重载或设置发布到正确的位置?
我可以从fiddler中获得所有操作方法(例如localhost/api/values).
asp.net asp.net-mvc asp.net-mvc-4 asp.net-web-api asp.net-web-api-routing
我正在与MVC 3 Web API中的路由问题作斗争.看起来应该很简单,但我没有取得任何进展.
我的错误是:
<Error>
<Message>The request is invalid.</Message>
<MessageDetail>
The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'Boolean NewViolationsPublished(Int32)' in 'BPA.API.Controllers.CacheManagementController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.
</MessageDetail>
</Error>
Run Code Online (Sandbox Code Playgroud)
我的RegisterRoutes是这样的:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "NukeAllItemsFromCache",
routeTemplate: "api/CacheManagement/NukeAllItemsFromCache");
routes.MapHttpRoute(
name: "ControllerAndAction",
routeTemplate: "api/{controller}/{action}"
);
routes.MapHttpRoute(
name: "ControllerAndActionAndId",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = …Run Code Online (Sandbox Code Playgroud) asp.net-mvc asp.net-mvc-3 asp.net-web-api asp.net-web-api-routing
在这里度过一段时间......(Web API 2.1,.NET 4.5.1)
我有一个完美的控制器:
[RoutePrefix("v1/members")]
public class MembersController : ApiController
{
[Route("{id}")]
public Member Get(string id)
{
DataGateway g = new DataGateway();
return g.GetMember(id);
}
}
Run Code Online (Sandbox Code Playgroud)
按预期和期望工作如下:
/v1/members/12345
但是我今天添加了一个新的控制器,它似乎根本没有注册或识别.它不会被添加到帮助页面,并在尝试访问时返回404 Not Found:
[RoutePrefix("v1/test")]
public class Test : ApiController
{
[Route("{id}")]
public string Get(int id)
{
return "value";
}
}
Run Code Online (Sandbox Code Playgroud)
就像我说的那样,新的控制器没有显示在帮助页面中并返回404:
/v1/test/12345

我究竟做错了什么?
编辑添加:
我安装了跟踪,它似乎没有达到那个目的.第一个控制器正常工作并显示跟踪,新的测试控制器不显示任何跟踪信息.
编辑2:
更新了示例代码以更好地匹配我的实际代码,这一直是问题所在.
在我的MVC和WebAPI应用程序中,我看到了两种不同的路由方式.
对于WebAPI:
WebApiConfig.CustomizeConfig(GlobalConfiguration.Configuration);
public static void Register(System.Web.Http.HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: ApiControllerOnly,
routeTemplate: "api/{controller}");
}
Run Code Online (Sandbox Code Playgroud)
对于MVC:
RouteConfig.RegisterRoutes(RouteTable.Routes);
public static void RegisterRoutes(System.Web.Routing.RouteCollection routes)
{
routes.MapRoute("DefaultRedirect",
"",
new { controller = "Home", action = "Index" });
}
Run Code Online (Sandbox Code Playgroud)
有人可以解释一下我在一个或另一个方法调用中注册路由有什么不同吗?另外,为什么一个人使用这种方式.
c# asp.net-mvc asp.net-mvc-routing asp.net-web-api asp.net-web-api-routing
我正在使用.NET Framework 4.5.1和C#开发ASP.NET Web Api 2.2应用程序.
我有一个这种方法的控制器:
public HttpResponseMessage Get(
string productCode,
byte codeLevel,
string productionOrderName,
string batchName,
string lineName,
int quantity)
{
Run Code Online (Sandbox Code Playgroud)
这就是我如何配置其路线WebApiConfig:
config.Routes.MapHttpRoute(
name: "ExternalCodesActionApi",
routeTemplate: "api/ExternalCodes/{action}/{productCode}/{codeLevel}/{productionOrderName}/{batchName}/{lineName}/{quantity}",
defaults: new { controller = "ExternalCodes" });
Run Code Online (Sandbox Code Playgroud)
但是现在我在同一个控制器(ExternalCodesController)上有另一种方法:
[HttpPut]
public HttpResponseMessage SetCodesAsUsed(List<string> codes)
{
Run Code Online (Sandbox Code Playgroud)
但是,使用该路由,当我使用该方法(http:// myHost:53827/api/ExternalCodes/SetCodesAsUsed)时,我得到一条InvalidOperationException消息:
"找到了与请求匹配的几个操作:
SetProCodesAsUsed类型MyProject.Web.API.Controllers.ExternalCodesController中的
SetCodesAsUnUsed类型MyProject.Web.API.Controllers.ExternalCodesController",
还有另一种方法ExternalCodesController:
[HttpPut]
public HttpResponseMessage SetCodesAsUnUsed(List<string> codes)
{
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
这些方法有不同的名称.
当我尝试不带可选参数的WebAPI控制器时遇到了404错误。我尝试将Global.asax.cs中的路线初始化命令重新排序无济于事。WebAPI在一个区域中,因此我注释掉该区域的路由信息,因此找不到该路由。这是我所拥有的:
在WebApiConfig.cs中:
public static void Register(HttpConfiguration configuration)
{
configuration.Routes.MapHttpRoute("DefaultAPI",
"API/{controller}/{action}/{id}",
new { id = RouteParameter.Optional });
// From http://weblogs.asp.net/fbouma/how-to-make-asp-net-webapi-serialize-your-llblgen-pro-entities-to-json
var json = configuration.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
json.SerializerSettings.ContractResolver = new DefaultContractResolver()
{
IgnoreSerializableInterface = true,
IgnoreSerializableAttribute = true
};
var appXmlType = configuration.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
configuration.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
Run Code Online (Sandbox Code Playgroud)
在APIAreaRegistration.cs中:
public override void RegisterArea(AreaRegistrationContext context)
{
//context.MapRoute(
// "API_default",
// "API/{controller}/{action}/{id}",
// new { action = "Index", id = UrlParameter.Optional }
//);
}
Run Code Online (Sandbox Code Playgroud)
在Global.asax.cs中:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
//WebApiConfig.Register(GlobalConfiguration.Configuration); …Run Code Online (Sandbox Code Playgroud) 我正在使用WebAPI 2 + ASP.NET Identity
在我的ApiController方法之一中,我想测试特定的HTTP请求是否来自经过身份验证的客户端(即,该请求是否包含授权标头)。
以下工作,但是也许有更好的方法?
private AuthContext db = new AuthContext();
// GET api/Orders/
[AllowAnonymous]
public async Task<IHttpActionResult> GetOrder(int id)
{
// ApplicationUser is an IdentityUser.
ApplicationUser currentUser = null;
try
{
UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
currentUser = await userManager.FindByNameAsync(User.Identity.GetUserName());
}
catch (Exception)
{
}
if ( currentUser == null )
{
// Anonymous request.
// etc...
} else {
// Authorized request.
// etc...
}
}
Run Code Online (Sandbox Code Playgroud)
我正在使用默认的路由模板。另一个选择是将两种方法路由到授权请求和匿名请求(用适当的数据注释装饰)。
asp.net-web-api asp.net-web-api-routing asp.net-identity asp.net-web-api2
我想将一堆数据,转换为json,作为字符串,发送到Web API POST方法.我可以发送一个简单的字符串,但是当我尝试发送字符串化的json数据时,甚至没有达到该方法 - 显然复杂的字符串不被视为有效的字符串值或其他东西.
当从客户端传递"randomString"时,这是有效的:
[Route("{unit}/{begindate}/{enddate}/{stringifiedjsondata}")]
[HttpPost]
public void Post(string unit, string begindate, string enddate, string stringifiedjsondata)
{
// test
string jsonizedData = stringifiedjsondata;
Run Code Online (Sandbox Code Playgroud)
string dataAsJson = "randomString";
String uriToCall = String.Format("/api/produceusage/{0}/{1}/{2}/{3}", _unit, beginRange, endRange, dataAsJson);
HttpResponseMessage response = await client.PostAsync(uriToCall, null);
Run Code Online (Sandbox Code Playgroud)
当字符串是json数据时,例如:
[
{
"ItemDescription": "DUCKBILLS, GRAMPS-EIER 70CT 42#",
"PackagesMonth1": 1467, . . . }]
Run Code Online (Sandbox Code Playgroud)
...这是行不通的.我通过使用JSON.NET将通用列表转换为json来创建此字符串,如下所示:
string dataAsJson = JsonConvert.SerializeObject(_rawAndCalcdDataAmalgamatedList, Formatting.Indented);
String uriToCall = String.Format("/api/produceusage/{0}/{1}/{2}/{3}", _unit, beginRange, endRange, dataAsJson);
HttpResponseMessage response = await client.PostAsync(uriToCall, null); …Run Code Online (Sandbox Code Playgroud) [Route("Street/{ZoneID}/{StreetID}/")]
public HttpResponseMessage GetStreet(int ZoneID,int StreetID,[FromUri] RealEstateFilter Filter)
Run Code Online (Sandbox Code Playgroud)
以下请求从客户端发送时,StreetID始终为0
HTTP://本地主机:1887 /街道/23295分之34MunZone = 7&的StartDate =&结束日期=
但它没有任何可选参数
我应该如何配置webapi才能阅读[Fromuri]