当我继承我的控制器形式ODataControllervs 时,有人能解释我ApiController吗?
问题是由返回的结果ApiController可以使用OData查询过滤的事实引起的.
如果我应用于QueraybleAttribute控制器的方法,即使操作返回,也会处理查询IEnumerable.
但是如果没有此属性但是通过调用config.EnableQuerySupport(),仅在方法返回时才处理查询IQueryable.
我认为这不是一致的行为.WebAPI 文档和示例意味着控制器必须从ODataController中删除.我有点困惑.
任一ApiController accidentally和部分地支撑部分(至少$跳过,$滤波器和$顶部)的OData协议.或者这是设计的,我需要ODataController来完成ODataSupport.
真正的问题是我的服务暴露了DTO,而不是POCO.可能没有一对一的映射.需要将OData查询再次转换为DTO到针对POCO的EF查询.
现在只玩OData.我检索实体并将它们转换为DTO.不可否认,对于每个请求来说,从数据库中获取所有这些数据并不是非常有效,但仍然可以容忍实验.但是,如果它需要一些过滤的DTO子集,则定义上不需要将所有实体返回给客户端.
OData查询开始使用ApiController和Querayble属性开箱即用,但前面提到的不一致使我做错了.
我有一个涉及杂草和杂草家庭的简单数据模型.
WeedFamily <-1---*-> Weed (WeedFamily和Weed有一对多的关系)
我正在尝试完成我的第一个ApiController,以便我可以轻松地将我的数据检索为AngularJS应用程序的JSON.当我/WeedAPI/在我的应用程序中访问URL时,出现以下错误.我很确定问题是我Weed和之间有循环引用WeedFamily.
我应该如何改变我的数据模型,使JSON序列化将同时保持的双向质量工作Weed- WeedFamily的关系?
(即我仍然希望能够构建如下表达式:
WeedData.GetFamilies()["mustard"].Weeds.Count
Run Code Online (Sandbox Code Playgroud)
和
WeedData.GetWeeds()[3].Family.Weeds
Run Code Online (Sandbox Code Playgroud)
)
错误:
<Error>
<Message>An error has occurred.</Message>
<ExceptionMessage>
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.
</ExceptionMessage>
<ExceptionType>System.InvalidOperationException</ExceptionType>
<StackTrace/>
<InnerException>
<Message>An error has occurred.</Message>
<ExceptionMessage>
Object graph for type 'WeedCards.Models.WeedFamily' contains cycles and cannot be serialized if reference tracking is disabled.
</ExceptionMessage>
<ExceptionType>
System.Runtime.Serialization.SerializationException
</ExceptionType>
<StackTrace>
at System.Runtime.Serialization.XmlObjectSerializerWriteContext.OnHandleReference(XmlWriterDelegator xmlWriter, Object obj, Boolean canContainCyclicReference) …Run Code Online (Sandbox Code Playgroud) 从几天前开始,我开始从我所有的Azure网站接收错误消息:
“找不到路径'/ admin / host / synctriggers'的控制器或未实现IController。”
这是我的匿名用户(或漫游器)来的。完整的错误消息如下。
这是什么意思,我应该担心其中涉及一些恶意活动吗?
Source : Error in: https://myproject.azurewebsites.net/admin/host/synctriggers?api-version=2018-11-01,
MemberName : Application_Error(Param : referrerUrl=),
SourceFilePath : C:\ProjectPath\Global.asax.cs,
Username : Anonymous
Date/Time : 20/7/2019 02:11:05
Stack Trace:
Message : The controller for path '/admin/host/synctriggers' was not found or does not implement IController.
Source : System.Web.Mvc
StackTrace : at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at MvcSiteMapProvider.DI.ControllerFactoryDecorator.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) …Run Code Online (Sandbox Code Playgroud) 我终于能够HttpContext.Current通过在线查找一些代码来获得不为空.但我仍然无法在单元测试中向请求添加自定义标头.这是我的测试:
[TestClass]
public class TagControllerTest
{
private static Mock<IGenericService<Tag>> Service { get; set; }
private TagController controller;
[TestInitialize]
public void ThingServiceTestSetUp()
{
Tag tag = new Tag(1, "people");
Response<Tag> response = new Response<Tag>();
response.PayLoad = new List<Tag>() { tag };
Service = new Mock<IGenericService<Tag>>(MockBehavior.Default);
Service.Setup(s => s.FindAll("username", "password", "token")).Returns(response);
controller = new TagController(Service.Object);
HttpContext.Current = FakeHttpContext();
}
public static HttpContext FakeHttpContext()
{
var httpRequest = new HttpRequest("", "http://kindermusik/", "");
var stringWriter = new StringWriter();
var httpResponce = new …Run Code Online (Sandbox Code Playgroud) c# unit-testing httprequest httpcontext asp.net-apicontroller
目前,我ApiController正在返回XML作为响应,但对于单个方法,我想返回JSON.即我无法进行全局更改以强制响应为JSON.
public class CarController : ApiController
{
[System.Web.Mvc.Route("api/Player/videos")]
public HttpResponseMessage GetVideoMappings()
{
var model = new MyCarModel();
return model;
}
}
Run Code Online (Sandbox Code Playgroud)
我尝试这样做,但似乎无法正确地将我的模型转换为JSON字符串:
var jsonString = Json(model).ToString();
var response = this.Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(jsonString, Encoding.UTF8, "application/json");
return response;
Run Code Online (Sandbox Code Playgroud) c# asp.net-mvc asp.net-web-api asp.net-apicontroller asp.net-web-api2
我一直在努力寻找,但却没有找到任何帮助.我哪里错了?我真的不知道该怎么办.我在下面写了所有细节.我尝试过但没有成功.
尝试创建"TypeNewsController"类型的控制器时发生错误.确保控制器具有无参数的公共构造函数.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
Bootstrapper.Run();
}
}
Run Code Online (Sandbox Code Playgroud)
我的apicontroller:
public class TypeNewsController : ApiController
{
private readonly ITypeNewsService _typeNewsService;
public TypeNewsController(ITypeNewsService typeNewsService)
{
_typeNewsService = typeNewsService;
}
[HttpGet]
public TypeNewsResponse Get([ModelBinder] PageRequest model)
{
model = model ?? new PageRequest();
var output = _typeNewsService.GetTypeNewss().ToList();
return new TypeNewsResponse
{
Page = model.PageIndex,
Records = model.PageSize,
Rows = output.ToList(),
Total = output.Count() / model.PageSize,
};
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
<Error>
<Message>An …Run Code Online (Sandbox Code Playgroud) asp.net-mvc dependency-injection autofac asp.net-apicontroller
我们有一个ASP.NET MVC应用程序,在没有针对IdentityServer3的问题的情况下进行身份验证,但是如果用户在大约3分钟后继续使用AJAX功能之前等待使用ApiController的应用程序的Web API部分开始失败(3分钟之前一切似乎都很好) .
Chrome中出现的错误包括:
XMLHttpRequest无法加载 https://test-auth.myauthapp.com/auth/connect/authorize?client_id=ecan-farmda ... gwLTk5ZjMtN2QxZjUyMjgxNGE4MDg2NjFhZTAtOTEzNi00MDE3LTkzNGQtNTc5ODAzZTE1Mzgw.请求的资源上不存在"Access-Control-Allow-Origin"标头.因此,不允许来源" http://test.myapp.com "访问.
在IE上我收到以下错误:
SCRIPT7002:XMLHttpRequest:网络错误0x4c7,操作被用户取消.
看看IdentityServer3的日志,我看到的条目如下:
2015-08-10 16:42 [警告](Thinktecture.IdentityServer.Core.Configuration.Hosting.CorsPolicyProvider)对路径的CORS请求:/ connect/authorize from origin:http://test.myapp.com 但拒绝因为无效CORS路径
在IdentityServer3 Web应用程序中,我向客户提供AllowedCorsOrigins:
Thinktecture.IdentityServer.Core.Models.Client client = new Thinktecture.IdentityServer.Core.Models.Client()
{
Enabled = configClient.Enabled,
ClientId = configClient.Id,
ClientName = configClient.Name,
RedirectUris = new List<string>(),
PostLogoutRedirectUris = new List<string>(),
AllowedCorsOrigins = new List<string>(),
RequireConsent = false, // Don't show consents screen to user
RefreshTokenExpiration = Thinktecture.IdentityServer.Core.Models.TokenExpiration.Sliding
};
foreach (Configuration.RegisteredUri uri in configClient.RedirectUris)
{
client.RedirectUris.Add(uri.Uri);
}
foreach (Configuration.RegisteredUri uri in configClient.PostLogoutRedirectUris)
{ …Run Code Online (Sandbox Code Playgroud) 我无法在web api控制器方法(SaveDetails)中获取JSON数组参数.
这是我的代码.
JavaScript代码:
$.ajax(
{
url : "api/Test/SaveDetails",
type : "POST",
data : {
"employees":
[
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
]
},
success: function (data) {alert("success");},
error: function () {alert("Error");}
})
控制器方法
[HttpPost]
public DataSet SaveDetails(Models.Person[] obj)
{
//save opertion.
}
Run Code Online (Sandbox Code Playgroud)
模型方法:
public class Person
{
public string firstName { get; set; }
public string lastName { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在web api方法中获取JSON数组参数有哪些更改.
我刚刚开始使用移动应用程序.我习惯用ApiControllerWeb API 制作API.
VS2015中的移动应用程序的默认项目模板附带了一个TodoItemController继承自的样本TableController.看起来有一些开箱即用的CRUD操作TableController,每个数据对象必须是类型ITableData.
理想情况下,我想跳过TableController并按照自己的方式实现ApiController.
我的问题是,TableController如果有的话,放弃的后果是什么?App Service和使用之间是否存在紧密耦合TableController?
问题:
我正在使用 NET Core 3.1 创建 API 应用程序。我想避免在每个ApiControllers和操作上设置路由属性。我尝试了很多组合UseEndpoints来设置常规路线,但我失败了。
对于某些配置,我无法使 Api 正常工作,而在其他一些配置中,我在启动过程中遇到此异常:
InvalidOperationException:操作“ApiIsWorking”没有属性路由。使用 ApiControllerAttribute 注释的控制器上的操作方法必须进行属性路由。
如何startup.cs使用类名和方法名设置自动映射控制器?
谢谢!
一些代码:
启动文件
...
services.AddControllers()
...
app.UseHttpsRedirection()
.UseRouting()
.UseAuthentication()
.UseEndpoints(endpoints => ?? )
.UseCoreHttpContext()
.UseServerConfiguration();
Run Code Online (Sandbox Code Playgroud)
控制器.cs
[ApiController]
public class BaseAPI : ControllerBase
{
[HttpGet]
public string ApiIsWorking()
{
return "API is working!";
}
}
Run Code Online (Sandbox Code Playgroud)
解决方案:
正如 Reza Aghaei 在解决方案中所说,错误是添加了 ApiController 属性。删除它后,命令 UseEndpoints 开始工作。
我的错误是添加属性以便能够识别应通过 API 公开哪些类。这是没有必要的,因为 UseEndpoints 只映射从 ControllerBase 继承的类。
警告:
2) 我强调了 Zinov …
c# asp.net-apicontroller asp.net-core asp.net-core-webapi asp.net-core-3.1
c# ×6
asp.net-mvc ×2
.net ×1
.net-4.5 ×1
ajax ×1
arrays ×1
asp.net-core ×1
autofac ×1
azure ×1
cors ×1
dto ×1
httpcontext ×1
httprequest ×1
odata ×1
oop ×1
unit-testing ×1