小编ono*_*012的帖子

ASP.NET WebApi - 一个控制器中的多个GET操作

我有Users控制器和基本的REST模式工作正常.但是我需要一个额外的模式users/{id}/usergroups来返回该用户的所有用户组.

实现这一目标的最佳方法是什么,因为我想我将需要更多控制器上的类似路由.只是默认的还不够......

错误

找到了与请求匹配的多个操作:Api.Models.Users.User GetUser(Int32)类型Api.Controllers.UsersController System.Collections.Generic.IEnumerable`1 [Api.Models.Users.UserGroup] GetUserGroups(Int32)on键入Api.Controllers.UsersController

// GET api/Users
public IEnumerable<User> GetUsers()

// GET api/Users/5
public User GetUser(int id) // THIS IS CONFLICT 1

// PUT api/Users/5
public HttpResponseMessage PutUser(int id, User user)

// POST api/Users
public HttpResponseMessage PostUser(User user)

// DELETE api/Users/5
public HttpResponseMessage DeleteUser(int id)

// GET api/Users/5/UserGroups
public IEnumerable<UserGroup> GetUserGroups(int id)  // THIS IS CONFLICT 2
Run Code Online (Sandbox Code Playgroud)

编辑1

我做了建议的amhed,它没有解决问题.

// GET api/Users/5
[HttpGet, ActionName("getuser")]
public User GetUser(int id) // …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-mvc-4 asp.net-web-api

18
推荐指数
1
解决办法
2万
查看次数

Gulp:控制台错误,assert.js:90抛出新的assert.AssertionError

我在控制台中遇到这样的错误:$ gulp

assert.js:90
  throw new assert.AssertionError({
  ^
AssertionError: Task function must be specified

at Gulp.set [as _setTask] (C:\Users\user\Projects\New project\node_modules\undertaker\lib\set-task.js:10:3)

at Gulp.task (C:\Users\user\Projects\New project\node_modules\undertaker\lib\task.js:13:8)

at Object.<anonymous> (C:\Users\user\Projects\New project\gulpfile.js:44:6)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
Run Code Online (Sandbox Code Playgroud)

这是我的gulpfile:

var gulp = require('gulp');
var build = require('gulp-build');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var browser_sync = require('browser-sync');
var gulps = require("gulp-series");


//gulp-build
gulp.task('build', function() {
    gulp.src('scripts/*.js')
        .pipe(build({
            GA_ID: …
Run Code Online (Sandbox Code Playgroud)

javascript gulp

15
推荐指数
2
解决办法
2万
查看次数

Gulp AssertionError [ERR_ASSERTION]:必须指定任务函数

这是我第一次在stackoverflow中请与我礼貌.

我在终端上使用MacOS Sierra 10.13.6,我正在尝试为AngularJS上构建的webapp演示自定义模板.我已经安装了Gulp,但是当我启动时gulp serve返回此错误而不启动本地服务器:

var gulp = require('gulp');
var args = require('yargs').argv;
var browserSync = require('browser-sync');
var config = require('./gulp.config')();
var del = require('del');
var $ = require('gulp-load-plugins')({lazy: true});

gulp.task('help', $.taskListing);
gulp.task('default', ['help']);

gulp.task('vet', function() {
    log('Analyzing source with JSHint and JSCS');

    return gulp
        .src(config.alljs)
        .pipe($.if(args.verbose, $.print()))
        .pipe($.jscs())
        .pipe($.jshint())
        .pipe($.jshint.reporter('jshint-stylish', {verbose: true}))
        .pipe($.jshint.reporter('fail'));
});

gulp.task('clean-tmp', function(done) {
    var files = config.tmp;
    clean(files, done);
});

gulp.task('clean', function(done) {
    var delconfig …
Run Code Online (Sandbox Code Playgroud)

assertion angularjs gulp

14
推荐指数
2
解决办法
5776
查看次数

asp.net身份userName是唯一的吗?

我正在阅读微软的用户身份,并试图在我的MVC5应用程序中应用它们.

据我所知,Id是关键,而userName不是键,定义说它可以为null,所以我问自己......为什么在MVC5项目模板中,当你输入一个已经存在的userName时你会收到错误信息??

我试图达到userName验证,但我不能.

这是数据库定义:

CREATE TABLE [dbo].[AspNetUsers] (
    [Id]            NVARCHAR (128) NOT NULL,
    [UserName]      NVARCHAR (MAX) NULL,
Run Code Online (Sandbox Code Playgroud)

这里是IdentityUser定义,通知(无验证):

namespace Microsoft.AspNet.Identity.EntityFramework
{
    public class IdentityUser : IUser
    {
        public IdentityUser();
        public IdentityUser(string userName);

        public virtual ICollection<IdentityUserClaim> Claims { get; }
        public virtual string Id { get; set; }
        public virtual ICollection<IdentityUserLogin> Logins { get; }
        public virtual string PasswordHash { get; set; }
        public virtual ICollection<IdentityUserRole> Roles { get; }
        public virtual string SecurityStamp { get; set; }
        public virtual string …
Run Code Online (Sandbox Code Playgroud)

c# asp.net validation asp.net-identity

11
推荐指数
2
解决办法
1万
查看次数

CSRF和RESTful API(symfony2,php)

我正在使用php/symfony2开发RESTful API.

Symfony2带有开箱即用的CSRF保护,它在使用普通表单数据时工作正常(它将CSRF令牌传递给表单,当发回时它需要嵌入表单中的相同令牌).

尽管如此,如果您开发RESTful API,此解决方案不适用于此目的,其中后端< - >前端之间的通信纯粹基于JSON.因此我禁用了CSRF.

我知道没有CSRF令牌是不安全的,所以我想知道什么是使用RESTful API获得CSRF的最佳方式.

一个想法是拥有特定的URL,例如/ api/generate/csrf,可以通过前端调用然后将令牌附加到json请求.它听起来不是最安全的方式,因为技术上可以由任何人生成令牌.

在开发RESTful API时,解决CSRF问题的最佳方法是什么?

干杯,理查德

php rest json csrf symfony

8
推荐指数
1
解决办法
2256
查看次数

Azure.Storage.Blobs v12.xx 中的 ContentHash 为 null

我正在尝试将我的项目从Microsoft.WindowsAzure.Storage v9(已弃用)升级到最新的 sdk Azure.Storage.Blobs v12。

我的问题(升级后)是访问ContentHash属性。

升级前步骤:

  1. 将文件上传到 blob
  2. CloudBlob.Properties.ContentMD5Microsoft.WindowsAzure.Storage.Blob获取上传文件的 MD5 哈希值
  3. 将计算出的 MD5 哈希值与从 azure 中检索到的值进行比较

升级后尝试访问 Azure 正在计算的 MD5 哈希值:

1.BlobClient.GetProperties()调用这个方法

2.BlobClient.UploadAsync()BlobContentInfo回复

两者都返回ContentHash为空。(请参阅我后来的问题以了解原因

我注意到的一个巨大差异是,使用较旧的 sdk,我可以告诉存储客户端使用 MD5 计算,如下所示:

CloudBlobClient cloudBlobClient = _cloudStorageAccount.CreateCloudBlobClient();

cloudBlobClient.DefaultRequestOptions.StoreBlobContentMD5 = true;

Run Code Online (Sandbox Code Playgroud)

所以我期待在最新的 sdk 上找到类似于StoreBlobContentMD5 的东西,但我不能。

谁能帮我找到这个问题的解决方案?

编辑 1: 我做了一个测试,在 azure 存储中我没有MD5 哈希

上传代码:

var container = _blobServiceClient.GetBlobContainerClient(containerName);
var blob = container.GetBlobClient(blobPath);

BlobHttpHeaders blobHttpHeaders = null;
if …
Run Code Online (Sandbox Code Playgroud)

c# azure

8
推荐指数
1
解决办法
688
查看次数

不支持写入压缩流.使用System.IO.GZipStream

尝试使用.NET框架中包含的GZipStream类解压缩(.gz)文件时出现异常.我正在使用MSDN文档.这是例外:

不支持写入压缩流.

这是应用程序源:

 try
 {
     var infile = new FileStream(@"C:\TarDecomp\TarDecomp\TarDecomp\bin\Debug\nick_blah-2008.tar.gz", FileMode.Open, FileAccess.Read, FileShare.Read);
     byte[] buffer = new byte[infile.Length];
     // Read the file to ensure it is readable.
     int count = infile.Read(buffer, 0, buffer.Length);
     if (count != buffer.Length)
     {
         infile.Close();
         Console.WriteLine("Test Failed: Unable to read data from file");
         return;
     }
     infile.Close();
     MemoryStream ms = new MemoryStream();
     // Use the newly created memory stream for the compressed data.
     GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Decompress, true);
     Console.WriteLine("Decompression");
     compressedzipStream.Write(buffer, 0, buffer.Length); //<<Throws error here …
Run Code Online (Sandbox Code Playgroud)

.net c# compression gzipstream

7
推荐指数
2
解决办法
9247
查看次数

实体框架6:检测关系变化

在我的DbContext子类中,我重写了SaveChanges()方法,因此我可以实现一种类似触发器的功能(在实际保存更改之前).现在,在某些触发器中,有必要检测某些关系是否已经改变,无论多对多,一对一/零等.

我已经阅读了互联网上的一些帖子,包括本网站上的一些帖子,提到DbContext API没有公开任何获取关系信息的方法.但是,ObjectContext应该能够.

我的SaveChanges方法:

public override int SaveChanges()
{
    IEntity entity;
    ChangeTracker.DetectChanges();

    var stateManager = ((IObjectContextAdapter)this).ObjectContext.ObjectStateManager;
    var added = stateManager.GetObjectStateEntries(EntityState.Added).ToList();
    var updated = stateManager.GetObjectStateEntries(EntityState.Modified).ToList();
    var deleted = stateManager.GetObjectStateEntries(EntityState.Deleted).ToList();
    var unchanged = stateManager.GetObjectStateEntries(EntityState.Unchanged).ToList();

    while ((entity = _entitiesRequiringTriggering.FirstOrDefault(x => x.Value).Key) != null)
    {
        _entitiesRequiringTriggering[entity] = false;
        var entry = ChangeTracker.Entries<IEntity>().SingleOrDefault(x => x.State != EntityState.Unchanged && x.Entity == entity);
        if (entry == null) continue;
        var trigger = Triggers.Triggers.GetTriggerForEntity(entry.Entity, this);
        if (trigger == null) continue;
        trigger.BeforeSave(entry.Entity);
        switch (entry.State)
        {
            case EntityState.Added:
                trigger.BeforeAdd(entry.Entity);
                break;
            case …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework foreign-keys

6
推荐指数
1
解决办法
5135
查看次数

如何使用c#中的行索引和列索引从datagridview获取单元格值?

我有一个datagridview dgvList ..然后我想获取特定行和列的单元格值,而不使用selectedRows属性.

即:

myvalue = dgvList[2nd row][1st column];
Run Code Online (Sandbox Code Playgroud)

c# datagridview

6
推荐指数
1
解决办法
3万
查看次数

ASP.NET在控制器上的未授权访问应该返回401而不是200和登录页面

ASP.NET 5应用程序中,我配置了MVC和Identity框架,如下所示:

app.UseMvc(config=>{
    config.MapRoute("Default", "{controller}/{action}/{id?}", new
            {
                controller = "Home",
                action = "Index"
            });
});
Run Code Online (Sandbox Code Playgroud)

并添加身份服务:

   services.AddAuthentication();
   services.AddAuthorization();

   services.AddIdentity<CrmUser, CrmUserRole>(config => { 
         config.User.RequireUniqueEmail = true;
          })
          .AddUserStore<MongoUserStore>()
          .AddRoleStore<MongoUserStore>()
          .AddDefaultTokenProviders();
Run Code Online (Sandbox Code Playgroud)

 app.UseIdentity()
    .UseCookieAuthentication(i => { i.LoginPath = "/Account/Login";});
Run Code Online (Sandbox Code Playgroud)

该示例定义如下:

public class MyApiController : Microsoft.AspNet.Mvc.Controller
{
    [Authorize]
    public async Task<ActionResult> Foo()
    {
        return Ok();
    }
}
Run Code Online (Sandbox Code Playgroud)

这工作正常,但我也有一些控制器,我想以API方式使用.在ASP.NET 5中,它们都具有相同的基类,因此API和视图控制器之间没有区别.

因此,当调用需要授权的未经授权的api时,我会得到一个HTTP 200和登录页面而不是HTTP 401.

Shawn Wildermuth的博客文章中,我发现了这一点

services.AddCookieAuthentication(config =>
    {
        config.LoginPath = "/Auth/Login";
        config.Events = new CookieAuthenticationEvents()
        { …
Run Code Online (Sandbox Code Playgroud)

asp.net asp.net-mvc asp.net-identity asp.net-core-mvc asp.net-core

6
推荐指数
1
解决办法
1166
查看次数