我正在尝试在IIS 6.0上运行ASP.NET MVC 3站点.
目前,当我从服务器请求页面时,它会出现以下错误:
分析器错误消息:在应用程序的预启动初始化阶段,无法调用此方法.
在这条线上:
<add name="MyMembershipProvider" type="NS.MyMembershipProvider" connectionStringName="MyDatabase" applicationName="/MySite"/>
Run Code Online (Sandbox Code Playgroud)
我完全难过,并且对ASP.NET应用程序生命周期没有太多线索,更不用说6.0和7.0之间的差异了.阅读它上面的MSDN页面似乎没什么帮助.
有没有人有任何见解或任何良好的调查链接?:)
我想在我的ASP.Net Web API Controller中返回一个文件,但我的所有方法都返回HttpResponseMessage为JSON.
public async Task<HttpResponseMessage> DownloadAsync(string id)
{
var response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent({{__insert_stream_here__}});
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return response;
}
Run Code Online (Sandbox Code Playgroud)
当我在浏览器中调用此端点时,Web API会返回设置HttpResponseMessage为HTTP Content Header 的as JSON application/json.
我有一些问题试图包装我的代码用于单元测试.问题是这样的.我有接口IHttpHandler:
public interface IHttpHandler
{
HttpClient client { get; }
}
Run Code Online (Sandbox Code Playgroud)
而使用它的类,HttpHandler:
public class HttpHandler : IHttpHandler
{
public HttpClient client
{
get
{
return new HttpClient();
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后是Connection类,它使用simpleIOC来注入客户端实现:
public class Connection
{
private IHttpHandler _httpClient;
public Connection(IHttpHandler httpClient)
{
_httpClient = httpClient;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我有一个单元测试项目,有这个类:
private IHttpHandler _httpClient;
[TestMethod]
public void TestMockConnection()
{
var client = new Connection(_httpClient);
client.doSomething();
// Here I want to somehow create a mock instance of the http client
// Instead of the …Run Code Online (Sandbox Code Playgroud) 我正在使用Chart.JS绘制数据集,
但是我的效果很好!
这是我得到的曲线:
这是我的代码:
function plotChart(data, labels) {
var lineChartData = {
"datasets": [{
"data": data,
"pointStrokeColor": "#fff",
"fillColor": "rgba(220,220,220,0.5)",
"pointColor": "rgba(220,220,220,1)",
"strokeColor": "rgba(220,220,220,1)"
}],
"labels": labels
};
var myLine = new Chart(document.getElementById("canvas").getContext("2d")).Line(lineChartData);
}
Run Code Online (Sandbox Code Playgroud)
我怎样才能有直线而不是曲线?
谢谢
我是XUnit和Moq的新手.我有一个方法,它将字符串作为参数.如何使用XUnit处理异常.
[Fact]
public void ProfileRepository_GetSettingsForUserIDWithInvalidArguments_ThrowsArgumentException() {
//arrange
ProfileRepository profiles = new ProfileRepository();
//act
var result = profiles.GetSettingsForUserID("");
//assert
//The below statement is not working as expected.
Assert.Throws<ArgumentException>(() => profiles.GetSettingsForUserID(""));
}
Run Code Online (Sandbox Code Playgroud)
正在测试的方法
public IEnumerable<Setting> GetSettingsForUserID(string userid)
{
if (string.IsNullOrWhiteSpace(userid)) throw new ArgumentException("User Id Cannot be null");
var s = profiles.Where(e => e.UserID == userid).SelectMany(e => e.Settings);
return s;
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试为调用异步存储库的类创建单元测试.我正在使用ASP.NET Core和Entity Framework Core.我的通用存储库看起来像这样.
public class EntityRepository<TEntity> : IEntityRepository<TEntity> where TEntity : class
{
private readonly SaasDispatcherDbContext _dbContext;
private readonly DbSet<TEntity> _dbSet;
public EntityRepository(SaasDispatcherDbContext dbContext)
{
_dbContext = dbContext;
_dbSet = dbContext.Set<TEntity>();
}
public virtual IQueryable<TEntity> GetAll()
{
return _dbSet;
}
public virtual async Task<TEntity> FindByIdAsync(int id)
{
return await _dbSet.FindAsync(id);
}
public virtual IQueryable<TEntity> FindBy(Expression<Func<TEntity, bool>> predicate)
{
return _dbSet.Where(predicate);
}
public virtual void Add(TEntity entity)
{
_dbSet.Add(entity);
}
public virtual void Delete(TEntity entity)
{
_dbSet.Remove(entity);
}
public virtual …Run Code Online (Sandbox Code Playgroud) 我试图将一个服务注入我的动作过滤器,但我没有在构造函数中注入所需的服务.这是我有的:
public class EnsureUserLoggedIn : ActionFilterAttribute
{
private readonly ISessionService _sessionService;
public EnsureUserLoggedIn()
{
// I was unable able to remove the default ctor
// because of compilation error while using the
// attribute in my controller
}
public EnsureUserLoggedIn(ISessionService sessionService)
{
_sessionService = sessionService;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
// Problem: _sessionService is null here
if (_sessionService.LoggedInUser == null)
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Result = new JsonResult("Unauthorized");
}
}
}
Run Code Online (Sandbox Code Playgroud)
而我正在装饰我的控制器:
[Route("api/issues"), EnsureUserLoggedIn]
public class IssueController : …Run Code Online (Sandbox Code Playgroud) 我正在构建ASP.NET Core WebAPI,我正在尝试为控制器编写单元测试.我发现的大多数示例都来自较旧的WebAPI/WebAPI2平台,似乎与新的Core控制器无关.
我的控制器方法正在返回IActionResults.但是,该IActionResult对象只有一个ExecuteResultAsync()需要控制器上下文的方法.我手动实例化控制器,因此此实例中的控制器上下文为null,这会在调用时导致异常ExecuteResultAsync.从本质上讲,这是让我走上一条非常黑客的道路,让这些单元测试成功完成并且非常混乱.我想知道必须有一种更简单/更正确的API控制器测试方法.
此外,如果有所不同,我的控制器不使用async/await.
我想要实现的简单例子:
控制器方法:
[HttpGet(Name = "GetOrdersRoute")]
public IActionResult GetOrders([FromQuery]int page = 0)
{
try
{
var query = _repository.GetAll().ToList();
int totalCount = query.Count;
int totalPages = (int)Math.Ceiling((double)totalCount / pageSize) - 1;
var orders = query.Skip(pageSize * page).Take(pageSize);
return Ok(new
{
TotalCount = totalCount,
TotalPages = totalPages,
Orders = orders
});
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
Run Code Online (Sandbox Code Playgroud)
单元测试:
[Fact]
public void GetOrders_WithOrdersInRepo_ReturnsOk()
{
// arrange
var …Run Code Online (Sandbox Code Playgroud) 当我尝试Configure在Startup.cs文件中的方法中使用自定义DbContext时,我收到以下异常.我在版本2.0.0-preview1-005977中使用ASP.NET Core
未处理的异常:System.Exception:无法为类型为"Communicator.Backend.Startup"的方法"Configure"的参数"dbContext"解析类型为"Communicator.Backend.Data.CommunicatorContext"的服务.---> System.InvalidOperationException:无法从根提供程序解析作用域服务"Communicator.Backend.Data.CommunicatorContext".
当我尝试接收其他实例时,也会抛出此异常.
未处理的异常:System.Exception:无法解析类型为"Communicator.Backend.Services.ILdapService"的服务
...
这是我ConfigureServices和Configure方法.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<CommunicatorContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddCookieAuthentication();
services.Configure<LdapConfig>(Configuration.GetSection("Ldap"));
services.AddScoped<ILdapService, LdapService>();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, CommunicatorContext dbContext, ILdapService ldapService)
{
app.UseAuthentication();
app.UseWebSockets();
app.Use(async (context, next) =>
{
if (context.Request.Path == "/ws")
{
if (context.WebSockets.IsWebSocketRequest)
{
WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
await Echo(context, webSocket);
}
else
{
context.Response.StatusCode = 400;
}
}
else
{
await next();
}
}); …Run Code Online (Sandbox Code Playgroud) c# dependency-injection .net-core asp.net-core asp.net-core-2.0
我正在尝试使用这段代码将文件保存在磁盘上.
IHostingEnvironment _hostingEnvironment;
public ProfileController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
[HttpPost]
public async Task<IActionResult> Upload(IList<IFormFile> files)
{
foreach (var file in files)
{
var fileName = ContentDispositionHeaderValue
.Parse(file.ContentDisposition)
.FileName
.Trim('"');
var filePath = _hostingEnvironment.WebRootPath + "\\wwwroot\\" + fileName;
await file.SaveAsAsync(filePath);
}
return View();
}
Run Code Online (Sandbox Code Playgroud)
我能代替IApplicationEnvironment与IHostingEnvironment,并ApplicationBasePath与WebRootPath.
似乎IFormFile不再具有SaveAsAsync()了.如何将文件保存到磁盘呢?